ServerSocket & multiple clients  
Author Message
Gargoyle





PostPosted: 2006-8-3 17:41:00 Top

java-programmer, ServerSocket & multiple clients Need help please.

I am trying to write a small client-server application that uses a
ServerSocket that allows connection of two clients via two ports (one on each
port, say 3000 & 4000).

I've tried different techniques, but always get the first client working but
the second client waiting until after the first client has ended (see code
snippet below).

How should I approach this (without the use of threads)?

(I am using the loopback address of "127.0.0.1" as both clients are on the
same PC)

private ServerSocket ss1;
private ServerSocket ss2;
private Socket socket1;
private Socket socket2;

try
{
ss1 = new ServerSocket(3000);
ss2 = new ServerSocket(4000);
}

and then

socket1 = ss1.accept();
socket2 = ss2.accept();

 
Gordon Beaton





PostPosted: 2006-8-3 18:55:00 Top

java-programmer >> ServerSocket & multiple clients On Thu, 03 Aug 2006 09:40:50 GMT, Gargoyle wrote:
> I am trying to write a small client-server application that uses a
> ServerSocket that allows connection of two clients via two ports
> (one on each port, say 3000 & 4000).

It might be worth knowing that *one* ServerSocket listening on *one*
port can handle *many* clients. You will get a unique Socket for each
connected client. Unless your clients are accessing completely
different service on the server, a single ServerSocket is the normal
way of doing this.

> I've tried different techniques, but always get the first client
> working but the second client waiting until after the first client
> has ended (see code snippet below).

Either use a separate thread for each ServerSocket, or use
Selector.select() to tell you when one of the ServerSockets has an
incoming connection that needs to be accepted.

Once you're able to accept() multiple clients, you still have the
problem of actually communicating with each of them, but the same two
solutions apply.

/gordon

--
[ don't email me support questions or followups ]
g o r d o n + n e w s @ b a l d e r 1 3 . s e