我想一次将一个以上的客户端连接到服务器,还要将服务器与所有客户端进行通信。
服务器如何识别每个客户端。以及如何将数据发送到特定客户端?

考虑,有3个客户A,B,C。所有客户端都已连接到服务器。服务器要向B发送消息。它是如何完成的?

最佳答案

如果我理解正确,那么您所需要做的就是不为一个连接绑定套接字。
您的客户端代码将如下所示:

客户类别:

public class TCPClient {

 public TCPClient(String host, int port) {

        try {
            clientSocket = new Socket(host, port);
        } catch (IOException e) {
            System.out.println(" Could not connect on port: " + port + " to " + host);
        }
}


服务器(主机)类:

   public class TCPListener {

    public TCPListener(int portNumber) {
            try {
                serverSocket = new ServerSocket(portNumber);
            } catch (IOException e) {
                System.out.println("Could not listen on port: " + portNumber);
            }
            System.out.println("TCPListener created!");
                    System.out.println("Connection accepted");
            try {
                while (true) {
                    Socket clientConnection = serverSocket.accept();

    //every time client's class constructor called - line above will be executed and new connection saved into Socket class.
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    }


那是最简单的例子。可以在这里找到更多信息:
http://www.oracle.com/technetwork/java/socket-140484.html

09-10 12:41
查看更多