I don't have any problem when I'm communicating with one client. The problem starts when I connect another client.The server eventually ignores the older clients and responds only to the latest one.
The working mechanism is simple: Accept connections and print messages received from multiple clients.
Client 1 (telnet localhost 5000)
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
1
1
1
1
1
1
1
1
1
111
Connection closed by foreign host
Client 2 (telnet localhost 5000) Latest client. Works properly.
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
2
2
2
2
2
2
2
2
2
2
2
222
Connection closed by foreign host.
Server output (java DebugServer 5000)
Server started
Incoming connection accepted
RECEIVED: 1
RECEIVED: 1
RECEIVED: 1
RECEIVED: 1
RECEIVED: 1
RECEIVED: 1
Incoming connection accepted
RECEIVED: 2
RECEIVED: 2
RECEIVED: 2
RECEIVED: 2
RECEIVED: 2
RECEIVED: 2
RECEIVED: 2
RECEIVED: 2
RECEIVED: 1
RECEIVED: 2
RECEIVED: 2
RECEIVED: 2
RECEIVED: 222
You can see that it isn't receiving the messages from the first client eventually. I tried debugging it using Netbeans and it shows nothing happens at bfr.readLine() when Client 1 sends a message after some messages have been sent.
Code:
import java.net.*;
import java.io.*;
import java.util.*;
public class DebugServer {
ServerSocket serverSocket;
BufferedReader bfr;
public static void main(String args[])
{
DebugServer server = new DebugServer();
server.go(Integer.parseInt(args[0]));
}
public void go(int portNo)
{
System.out.println("Server started");
try {
serverSocket = new ServerSocket(portNo);
while(true) {
Socket socket = serverSocket.accept();
System.out.println("Incoming connection accepted");
ClientSession c = new ClientSession(socket);
Thread t = new Thread(c);
t.start();
}
} catch(IOException e)
{
System.out.println("Server IOException");
e.printStackTrace();
}
}
class ClientSession implements Runnable{
Socket socket;
ClientSession(Socket socket)
{
this.socket = socket;
}
public void run() {
try{
InputStreamReader isr = new InputStreamReader(socket.getInputStream());
bfr = new BufferedReader(isr);
String s;
for(;;) {
while((s = bfr.readLine()) != null) {
System.out.println("RECEIVED: "+s);
}
}
} catch(IOException e) {
System.out.println("Server IO Exception");
}
}
}
}
Thank you for your help.