如何让多个客户端与服务器通信?

How to enable multiple clients to communicate with the server?

我遇到的问题是我不确定如何让多个客户端通过线程与服务器通信,我已经尝试过了,但我认为做错了什么。任何帮助将不胜感激。

import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer {
    ArrayList clientOutputStreams;

    public class ClientHandler implements Runnable {
        BufferedReader reader;
        Socket sock;

        public ClientHandler(Socket clientSocket) {
            try {
                sock = clientSocket;
                InputStreamReader isReader = new InputStreamReader(
                        sock.getInputStream());
                reader = new BufferedReader(isReader);
            } catch (Exception x) {

            }
        }

        public void run() {
            String message;
            try {
                while ((message = reader.readLine()) != null) {
                    System.out.println("read" + message);
                    tellEveryone(message);
                }
            } catch (Exception x) {

            }
        }
    }

    public void go() {
        clientOutputStreams = new ArrayList();
        try {
            ServerSocket serverSock = new ServerSocket(5000);

            while (true) {
                Socket clientSocket = serverSock.accept();
                PrintWriter writer = new PrintWriter(
                        clientSocket.getOutputStream());
                clientOutputStreams.add(writer);

                Thread t = new Thread(new ClientHandler(clientSocket));
                t.start();
                System.out.println("got a connection");
            }
        } catch (Exception x) {

        }
    }

    public void tellEveryone(String message) {
        Iterator it = clientOutputStreams.iterator();
        while (it.hasNext()) {
            try {
                PrintWriter writer = (PrintWriter) it.next();
                writer.println(message);
                writer.flush();
            } catch (Exception x) {

            }
        }
    }

    public static void main(String[] args) {
        new ChatServer().go();
    }`enter code here`

}

要允许多个客户端连接到您的服务器,您需要一个服务器不断寻找要连接的新客户端。这可以像这样完成:

while(true) {
    Socket socket = Ssocket.accept();
    [YourSocketClass] connection = new [YourSocketClass](socket);
    Thread thread = new Thread(connection);
    thread.start();
}

这可能也最好在单独的服务器 java 文件中完成,该文件可以 运行 独立于客户端。