I have a server class which connects a client on a specific server socket port and starts off a thread with a service class. Specifically, I have 3 service classes so I would like to have 3 different ports. This however, is not working as I had expected it to. This is my code for the server:
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
public class WebsiteServer {
public static void main(String args[]) throws IOException {
ServerSocket serversocket = new ServerSocket(22401);
ServerSocket serversocket2 = new ServerSocket(22402);
Thread thread;
Thread thread2;
Socket socket;
Socket socket2;
NewUserService newuserservice;
ExistingUserService existinguserservice;
System.out.println("Waiting for clients to connect.");
while (true) {
socket = serversocket.accept();
socket2 = serversocket2.accept();
if(socket.isConnected()) {
System.out.println("NewUserClient has connected.");
newuserservice = new NewUserService(socket);
thread = new Thread(newuserservice);
thread.start();
}
if(socket2.isConnected()) {
System.out.println("ExistingUserClient has connected.");
existinguserservice = new ExistingUserService(socket2);
thread2 = new Thread(existinguserservice);
thread2.start();
}
}
}
}
It works fine if I only use one port for example:
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
public class WebsiteServer {
public static void main(String args[]) throws IOException {
ServerSocket serversocket = new ServerSocket(22401);
ServerSocket serversocket2 = new ServerSocket(22402);
Thread thread;
Thread thread2;
Socket socket;
Socket socket2;
NewUserService newuserservice;
ExistingUserService existinguserservice;
System.out.println("Waiting for clients to connect.");
while (true) {
socket = serversocket.accept();
//socket2 = serversocket2.accept();
if(socket.isConnected()) {
System.out.println("NewUserClient has connected.");
newuserservice = new NewUserService(socket);
thread = new Thread(newuserservice);
thread.start();
}
// if(socket2.isConnected()) {
//
// System.out.println("ExistingUserClient has connected.");
// existinguserservice = new ExistingUserService(socket2);
// thread2 = new Thread(existinguserservice);
// thread2.start();
// }
}
}
}
Any help would be appreciated.
The accept method blocks until a connection is made. So, you are sitting blocked one one .accept(), even though the other server may have activity. One simple solution would be to make one listening thread per server.