Alon Dattner Alon Dattner - 2 months ago 21
Java Question

Get client id using multithreaded java server

I'm currently trying to create a multithreaded java socket server.
I can send "private" messages using "ID;MESSAGE; in my clients.

The messages arrive at the right client but the problem is that the server always displays that all messages come from the same client (client id 0), but they don't.

Here's my Server http://pastebin.com/Dzh5Ynvj

Server output

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

Answer

In your ClientHandler code, you have not assigned the id parameter to the id member of your class.

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();
    }
}

Add this.id = id; in your ClientHandler constructor. That should do it.

Comments