Home  >  Article  >  Java  >  How to create a multi-threaded LAN chat room using Java

How to create a multi-threaded LAN chat room using Java

王林
王林forward
2023-05-09 12:34:141269browse

1.TCP

To achieve a LAN connection, you must know the principle of information transmission.
The information transmitted in the LAN is in the form of packets. I use TCP packets to transmit data, and IP packets are encapsulated in the TCP packets.
The following sentence is to obtain the IP address of a server through a static IPV4 protocol class.

address = InetAddress.getByName("192.168.43.86");

2. Socket

The IP address of the server is obtained in TCP, but the specific application cannot be locked based on the IP address alone, so the concept of socket is introduced. The port number is used to lock the host's process. The port number is generally 1024~49151, because 0~1023 is a well-known port number and is generally used for some commonly used ports such as HTTP. 49152~65535 is a temporary port number and cannot be occupied randomly. It is usually temporarily allocated during the running of the program. .
Socket=IP port number
This sentence defines a socket with port number 9998 and IP 192.168.43.86.

int port = 9998;
socket = new Socket(address,port);

3.C/S architecture

How to create a multi-threaded LAN chat room using Java

From the perspective of Java classes, the server and client abstract a connection through socket connections. The server realizes the information reading function by establishing its own socket port and monitoring whether a client connects to this port. The client transmits data to the server through the port number agreed by the server. After the server is turned on, run the client and perform a three-way handshake with the server to establish a TCP connection. Then, based on this connection, communication between the client and the server is realized.

4. Multi-threading

Since the server may serve multiple objects at the same time, if the traditional method is used for server connection, there will be multiple clients waiting for one client to interact with the server. . In order to solve this problem, a multi-threading approach is adopted.
Use the SuperSocket class to inherit the socket class and implement the Runnable interface to achieve multi-threaded operation.

class SuperSocket extends Socket implements Runnable
SuperSocket socket_1 = new SuperSocket(9999);
SuperSocket socket_2 = new SuperSocket(9998);
SuperSocket socket_3 = new SuperSocket(9997);
Thread s1 = new Thread(socket_1);
Thread s2 = new Thread(socket_2);
Thread s3 = new Thread(socket_3);

5. Server

The server’s architecture is shown in the third part, and the code is implemented as follows

package TCP;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TCPserver2 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        //实例化具有多线程功能的服务器专用socket类
        //需要传递端口号作为初始化变量
        SuperSocket socket_1 = new SuperSocket(9996);
        SuperSocket socket_2 = new SuperSocket(9998);
        SuperSocket socket_3 = new SuperSocket(9997);
        //建立三个子线程
        Thread s1 = new Thread(socket_1);
        Thread s2 = new Thread(socket_2);
        Thread s3 = new Thread(socket_3);
        try {
            while(true) {
            	//开启线程
                s1.start();
                s2.start();
                s3.start();
                if(scan.next()=="123"){
                //结束线程
                    break;
                }
            }
        } finally {
            try {
            //关闭套接字
                socket_1.close();
                socket_2.close();
                socket_3.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class SuperSocket extends Socket implements Runnable{

    InputStream is;
    byte[] buffer;
    Socket socket=null;
    ServerSocket serverSocket=null;

    public SuperSocket(int port){
        try {
        //初始服务器型套接字
            serverSocket = new ServerSocket(port);
            buffer = new byte[1024];

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        try {
        	//等待端口连接
            socket = serverSocket.accept();
            //连接完成后创建输入流
            is = socket.getInputStream();
            //读取客户端传送信息
            int len = is.read(buffer);
            String str = new String(buffer, 0, len);
            System.out.println(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Client

The client’s architecture is shown in the third part As shown, the code implementation is as follows

package TCP;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class TCPclient {
    public static void main(String[] args) {
        InetAddress address=null;
        Socket socket=null;
        OutputStream os=null;
        String message=null;
        Scanner sca=null;
        try {
            //得到本机IP地址
            address = InetAddress.getByName("192.168.43.86");
            //规定端口号,建立套接字
            int port = 9998;
            socket = new Socket(address,port);
            //绑定套接字的输出流
            os = socket.getOutputStream();
            sca = new Scanner(System.in);
            while(true) {
                message = sca.next();
                //写入输出流,在局域网中传输
                os.write(message.getBytes());
            }

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
            //关闭端口号,关闭io流
                os.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

The above is the detailed content of How to create a multi-threaded LAN chat room using Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete