Have a question about multiple clients connecting a single server. Here is my server side code:
//...
ServerSocket serverSocket = null;
try{
serverSocket = new ServerSocket(port);
}catch(IOException e){
e.printStackTrace();
}
Socket server = null;
while(true){
try{
server = serverSocket.accept();
new createdThread(server).start(); //This is a thread class specified somewhere else to handle the socket.
}catch(IOException e){
e.printStackTrace();
}
createdThread()
is a thread that will start to handle the socket, and it takes the Socket server
as an argument. Suppose I have a connection and a thread starts, the accepted socket was passed to the thread as an argument. In this case, server
should be passed as a reference if I'm not wrong. If before the end of the first thread, serverSocket
gets a new connection and create a new socket, which will change the value of server
. Will this impact the execution of the first thread since the first thread takes the reference as its argument, meaning the underlying object of that reference is changed?
I tested the program and it seemed working well. Each thread was not impacted by each other, although all of their constructor arguments are references to the same object. This does not make sense to me, and hope someone could clarify. Thanks.