You should have just one ServerSocket
listening on a port that is known to the client. When a client connects to the server, a new Socket
object is created and the original ServerSocket
goes back to listening again. You should then spin off a new Thread
or hand over to an Executor
the actual work of talking to the client, otherwise your server will stop listening for client connections.
Here is a very basic sketch of the code you will need.
import java.net.*;
import java.util.concurrent.*;
public class CoordinateServer {
public static void main(String... argv) throws Exception {
// 'port' is known to the server and the client
int port = Integer.valueOf(argv[0]);
ServerSocket ss = new ServerSocket(port);
// You should decide what the best type of service is here
ExecutorService es = Executors.newCachedThreadPool ();
// How will you decide to shut the server down?
while (true) {
// Blocks until a client connects, returns the new socket
// to use to talk to the client
Socket s = ss.accept ();
// CoordinateOutputter is a class that implements Runnable
// and sends co-ordinates to a given socket; it's also
// responsible for cleaning up the socket and any other
// resources when the client leaves
es.submit(new CoordinateOutputter(s));
}
}
}
I have put sockets here since they are easier to get started with, but once you have this working well and want to boost your performance you will probably want to investigate the java.nio.channels
package. There's a good tutorial over at IBM.
ExecutorService
here. – Protectorate