I'm doing a little client/server app. For now it's functioning well, but I need to add an "option".
The server class is like this:
public class Server {
public static void main(String[] zero) throws IOException {
ServerSocket serverSocket ;
Socket clientSocket ;
DataBase DB = new DataBase();
System.out.println("ouverture du server");
serverSocket = new ServerSocket(2000);
DB.printAll(); //just to see the DB.
while(true) {
try {
clientSocket = serverSocket.accept();
Thread t = new Thread(new Connect(clientSocket, DB));
t.start();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
So a lot of clients are able to connect to the server. My point is: I want a connected client (say, Client1) to be able to send something to another connected client (Client2) of his choice.
And my problem: how can Client1 find/have/retrieve the socket of Client2, since all client connect to the server through this clientSocket in different threads?
I've read this which propose to make a list of dataoutputstream containing the outputStream of each connected client. This seem like a good idea, but I would prefer to do the same with sockets (because I'm not sure if I'll need the "data" output stream or another output stream for now, and in any case it'll be more clear for me with the sockets).
Plus, Client2 is doing his own stuff with the server, which includes exchange data, so he'll use his output/input stream. I have to make sure that this won't mix up.
For example, say Client2 send something to server and wait a response. Then Client1 send something to Client2; instead of the server response, Client2 receive what Client1 send; as he wasn't suppose to receive that, this lead to fatal error.
I've read something about synchronized threads, it seems to be what I need, but I'm new to java and this is a bit hard?
I think if I declare the Client2 Socket as synchronized, then the thread will wait until clientSocket is free before using it; and since the client isn't supposed to disconnect (and if he does, well the socket is closed so we can't send him anything), the thread (of client1) won't be able to use the socket of client2.
Now, if I synchronize the DataOutputStream, sometimes communication between client2 and server involves many different outputstream, so the DataOutputStream can be free to use, but the Client2 will still be waiting for an input from server, not from Client1, so not the same input.
Maybe I can synchronise directly the complete OutputStream. Or maybe what I said just doesn't have any sense. Help?