Re: Basic SocketServer & Thread Question
- From: Esmond Pitt <esmond.nospam.pitt@xxxxxxxxxxxxxxxxxx>
- Date: Fri, 03 Jun 2005 08:45:11 GMT
Lee Fesperman wrote:
shakah wrote:
john wrote:
How could I have a SocketServer accept connections from a handful of known IP addresses, when the connections come and go in random order? Right now I have one instance of ServerSocket accepting connections from all client IP addresses:
ServerSocket ss = new ServerSocket(5000); // listen on port 5000 while (true) { Socket s = serverSocket.accept(); (new MyProcessor(s)).start(); // process stream in a new thread }
But I want to bind to only specific IP addresses, something like this:
static final String[] validIP = {"100.200.300.1", "100.200.300.2", "100.200.300.3"}; while (true) { for (int i=0; i<validIP.length; i++) { Socket s = serverSocket.bind(new InetSocketAddress(validIP[i], 5000)); (new MyProcessor(s)).start(); // process stream in a new thread } }
But this design requires the clients to connect in order. I could create a thread that waits for a connection from each valid IP, but that would mean having multiple instances of ServerSocket, and multiple ServerSocket instances cannot listen to the same port number simultaneously. What can I do?
Any hints or examples would be appreciated. I could just have MyProcessor disconnect if it's not a valid address, but I was looking for a more elegant solution.
Thanks.
-John
Try extending your first example to use Socket.getInetAddress().getHostAddress() on the accept'ed socket, e.g. something like:
ServerSocket ss = new ServerSocket(5000); // listen on port 5000 while (true) { Socket s = serverSocket.accept(); String sIncomingHostAddress = s.getInetAddress().getHostAddress() ; if(/*sIncomingHostAddress is in list of acceptable hosts*/) { (new MyProcessor(s)).start(); // process stream in a new thread } else { s.close() ; } }
That's a reasonable solution depending on the circumstances. Alternatively, you can create a ServerSocket for each acceptable host and do accepts in separate threads.
I don't understand how this suggestion is supposed to work but you can also control the hosts which are accepted via a policy file SocketPermission/accept setting if you are prepared to let a SecurityManager loose.
.
- Follow-Ups:
- Re: Basic SocketServer & Thread Question
- From: Lee Fesperman
- Re: Basic SocketServer & Thread Question
- References:
- Basic SocketServer & Thread Question
- From: john
- Re: Basic SocketServer & Thread Question
- From: shakah
- Re: Basic SocketServer & Thread Question
- From: Lee Fesperman
- Basic SocketServer & Thread Question
- Prev by Date: Re: how to compute for CRC-16?
- Next by Date: Re: Optimise my ray tracer
- Previous by thread: Re: Basic SocketServer & Thread Question
- Next by thread: Re: Basic SocketServer & Thread Question
- Index(es):
Relevant Pages
|