Two TCP Servers (threads) on the same computer

S

Sona

Hi,

I want to create different threads that will run from the same program
and will listen for incoming TCP Connections. Doing this with a single
thread works fine.. but when I try to launch another thread, it says
java.net.BindException: Address already in use: JVM_Bind.

I even tried making the second thread listen on a different port but
this is not working. How can I make this work? Thanks


Sona
 
G

Gordon Beaton

I want to create different threads that will run from the same
program and will listen for incoming TCP Connections. Doing this
with a single thread works fine.. but when I try to launch another
thread, it says java.net.BindException: Address already in use:
JVM_Bind.

I even tried making the second thread listen on a different port but
this is not working. How can I make this work? Thanks

There should be no problem creating a second ServerSocket that listens
on a *different* port number, I can't say why that didn't work for you
without seeing any code.

However for a given port number, there can be only one ServerSocket
(unless they also specify different local addresses), which is why
your attempt to create two failed. You could create the ServerSocket
once and wait in accept() from different threads, but that isn't the
normal way to handle multiple connections.

Instead, have one thread that creates the ServerSocket and listens for
incoming connections. As each connection arrives, create a thread to
handle the resulting Socket (or perhaps pass it to a thread pool):

ServerSocket ss = new ServerSocket(port);

while (!done) {
Socket s = ss.accept();
Runnable r = new MyRunnable(s);
Thread t = new Thread(r);
t.start();
}

Your "MyRunnable" should close the Socket before terminating.

/gordon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top