Re: socket server
On Mon, 17 Sep 2007 04:40:34 -0700, korcs wrote:
I replaced the catch block with:
//System.exit(-1);
finalize();
listenSocket();
SO it works.
In finalize() you close not only the client socket, but also the
ServerSocket. It's sufficient to close the client socket if you intend
to handle additional clients, and reuse the same Serversocket.
Also, by calling listenSocket recursively, you will run into stack
depth problems after some number of clients have been handled. Use a
loop instead.
But the question is still there, how can I handle multiple clients
on the same port?
Your server loop should look like this:
ServerSocket ss = new ServerSocket(...);
while (!done) {
Socket s = ss.accept();
MyClient c = new MyClient(s); // extends Runnable
Thread t = new Thread(c);
t.start();
}
By spawning a thread to handle each client, the server loop can
immediately go back to waiting for the next client to connect. This
lets you handle multiple clients simultaneously. If you only need to
handle them one at a time, you don't need the Thread, just call a
method in the client object and wait until it returns.
In your MyClient class, keep whatever state you need to handle one
client, including the client socket. When you are finished handling
the client, close the socket!
/gordon
--