-
Server Socket
Hey guys, I'm trying to create a pretty simple Server/Client application that communicates back and forth. My problem is that as multiple clients join, the server only responds to the latest client connected, regardless of which client asks for the response. For example:
Server Starts
Client 1 connects
Client 1 asks for Response
Server Responds to client 1
Client 2 connects
Client 1 asks for Responses
Server Responds to client 2
Here is the code
Code:
import java.net.*;
import java.io.*;
public class mainServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
int port = 5555;
try {
serverSocket = new ServerSocket(port);
System.out.println("Server started...Running Mode");
} catch (IOException e) {
System.err.println("Could not listen on port: " + port);
System.exit(1);
}
while(listening){
new clientConnectedThread( serverSocket.accept() ).start();
}
serverSocket.close();
}
}
class clientConnectedThread extends Thread {
private Socket clientSocket = null;
private static PrintWriter out = null;
public clientConnectedThread(Socket socket){
super("clientConnectedThread");
clientSocket = socket;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine;
boolean Listening = true;
out.println("Welcome to the Server");
this.setName(in.readLine());
System.out.println("Client: successfully connected...");
while(Listening){
inputLine = null;
inputLine = in.readLine();
if(inputLine.equals("talkback")){
out.println("Message Recieved");
}
if(inputLine.equalsIgnoreCase("exit"))
break;
}
out.close();
in.close();
clientSocket.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
This has me baffled because the way i understand the code is that when I create this new thread, a specific outputStream() is created for this particular thread and it should be bound to the client that opened the socket. However, clearly I am wrong and mis-understand this. If anyone could give me a better understanding on how the relationship works between this Thread and the client that opened the socket (which ultimately spawned the Thread), please let me know.
Any help is appreciated...Thanks
-
Please forgive my stupidity. Its 1AM and I've been drinking.
The above problem was solved.
Keyword in the code to look for....
"static"....
FML