使用多线程Java服务器获取客户端ID

时间:2016-09-14 04:15:12

标签: java multithreading sockets networking server

我目前正在尝试创建一个多线程的Java套接字服务器。 我可以使用“ID; MESSAGE;在我的客户中发送”私人消息。

消息到达正确的客户端但问题是服务器始终显示所有消息来自同一客户端(客户端ID为0),但他们没有。

这是我的服务器http://pastebin.com/Dzh5Ynvj

服务器输出

21:02:55 [DSS-Server] [Client#0] connected.
21:02:58 [DSS-Server] [Client#1] connected.
21:13:11 [DSS-Server] [Client#0] > 0;This is send from client 0
21:13:18 [DSS-Server] [Client#0] > 1;This also
21:13:30 [DSS-Server] [Client#0] > 0;But this comes from client 1

1 个答案:

答案 0 :(得分:0)

在您的ClientHandler代码中,您尚未将id参数分配给班级的id成员。

public ClientHandler(Socket client, int id) {
   this.id = id; // ADD THIS LINE
    try {

        //Get BufferedReader from client
        this.client = client;
        reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

this.id = id;构造函数中添加ClientHandler。应该这样做。

相关问题