1

I have a requirement where I need to open two ServerSockets at a time and listen to both for their respective sockets continuosly.

These are working individually fine, but I need to work them together.

while(true){
    Socket socket = serversocket1.accept()
    new SocketProcessor(socket).start(); 
}

while(true){
    Socket socket = serversocket2.accept()
    new AnotherSocketProcessor(socket).start(); 
}

How can I do this?

2 Answers2

1

You can refer this from here. You have to use multi threading....

Listening to two ports simultaneously in Java server using multithreading

Community
  • 1
  • 1
ashokramcse
  • 2,841
  • 2
  • 19
  • 41
  • Thanks for the response.. I will check and will let u know. –  Mar 14 '14 at 17:56
  • Plz see my comment on Dmitriy Solution. Your solutions will also gv me same problem. –  Mar 14 '14 at 18:23
0

Did you consider multi-threading?

First, we create a class implementing the Runnable interface.

class SocketListenerRunnable implements Runnable {
    ServerSocket serverSocket;
    SocketProcessor socketProcessor;

    public void setServerSocket (ServerSocket serverSocket) {
        this.serverSocket = serverSocket;
    }

    public void setSocketProcessor (SocketProcessor socketProcessor) {
        this.socketProcessor = socketProcessor;
    }

    public void run () {
        while (true) {
            Socket socket = serverSocket.accept ();
            socketProcessor (socket).start ();
        }
    }
}

Then we just use it when needed.

SocketListenerRunnable r1 = new SocketListenerRunnable ();
r1.setServerSocket (serverSocket1);
r1.setSocketProcessor (socketProcessor1);
Thread t1 = new Thread (r1);
t1.start ();

SocketListenerRunnable r2 = new SocketListenerRunnable ();
r2.setServerSocket (serverSocket2);
r2.setSocketProcessor (socketProcessor2);
Thread t2 = new Thread (r2);
t2.start ();
  • Will it arose a problem, that will be infinite Socket objects inside "r" ? –  Mar 14 '14 at 18:19
  • Well, it should not, since the socket processors are started in the same threads as the sockets are accepted. So, until the SocketProcessor.start() method ends, a new Socket instance will not be received. And when SocketProcessor.start() ends, the old Socket instance will be forgotten. – Dmitriy Merkushov Mar 14 '14 at 20:31