Well, to be honest it works just for one client, don’t really know why. Also client is receiving everything two or three times. [ I’ve used telnet as a client. When I start another telnet session, it stays, but it doesn’t give any output ].
I will add gui code if needed.
public static void main(String args[]) throws IOException {
String s;
initGUI();
try {
hostServer = new ServerSocket(port);
socket = hostServer.accept();
area.append(" "+socket+" connection\n");
changeStatusTS(CONNECTED, true);
} catch (IOException e) {
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.out.println(e);
}
while(true) {
multi ml = new multi(socket);
ml.start();
}
}
}
static class multi extends Thread{
public multi(Socket c) throws IOException {
socket = c;
}
public void run(){
String s;
switch (connectionStatus) {
case CONNECTED:
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
if (toSend.length() != 0) {
out.print(toSend); out.flush();
toSend.setLength(0);
changeStatusTS(NULL, true);
}
if (in.ready()) {
s = in.readLine();
if ((s != null) && (s.length() != 0)) {
if(s.equals("test")==true){
out.print("bazinga");
out.flush();
}
if (s.equals(END_CHAT_SESSION)) {
changeStatusTS(DISCONNECTING, true);
}
else {
appendToChatBox("INCOMING: " + s + "\n");
changeStatusTS(NULL, true);
}
}
}
}
catch (IOException e) {
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case DISCONNECTING:
out.print(END_CHAT_SESSION);
out.flush();
cleanUp();
changeStatusTS(DISCONNECTED, true);
break;
default: break;
}
}
}
}
I’ve not looked at the entire code but an immediate problem looks to be that your server is not calling
accept()in a loop. I’d change yourmainto be something like the following:When a client calls connection, the server’s
accept()call returns and your code should create a newMultithread to handle that connection. Then the server should loop around and callaccept()again, waiting for the next client to connect.Hope this helps.