Hi All, I was running the examples supplied by Javaworld - Socket. In this example, there is a server and client program. I have the server running in one jvm I start the client on another jvm post requests to server. I get the feedback from the server and the client program ends. Now, if i start the client again then the server doesn't respond back. If i kill the server and start over again everything works properly Any ideas what the problem is? I always thought if the socket is closed by a client then the socket is freed for further requests. Did i get something wrong?
I went and looked at the example code you cited; it's actually written such that the server can only handle one client and then exit, so what you're seeing is the expected behavior. This is a pretty bad example to start from. What a real server needs to do is call accept() in a loop; each call to accept() returns a Socket representing a new client connection, and the server generally spawns a separate thread in which to handle that one client and then llops back to call accept() again. Much higher quality sample code (with significantly fewer typos!) is available in Sun's networking tutorial.
Thank you very much Ernest for referring the Sun's tutorial. However,when I was going through the tutorial there was a mention of
The KnockKnockClient program also specifies the port number 4444 when creating its socket. This is a remote port number--the number of a port on the server machine--and is the port to which KnockKnockServer is listening. The client's socket is bound to any available local port--a port on the client machine. Remember that the server gets a new socket as well. That socket is bound to a local port number (not port 4444) on its machine. The server's socket and the client's socket are connected
I din't quite clearly understand what this actually meant. Does this mean for each port there can be multiple sockets(so to say, local port numbers) in each machine? So when would Server / Client would receive an exception "Port already used up" ?
Does this mean for each port there can be multiple sockets(so to say, local port numbers) in each machine?
Yes that is true! For instance, three connections among three hosts denoted by ip1, ip2 and ip3: ip1: port1 <---> ip2: port1234 ip1: port2 <---> ip2: port1234 ip2: port1 <---> ip2: port1234 A connection is made up by two ips and two ports. The two comunications between hosts ip1 and ip2 are distinguishable because the first one has port1 at the host ip1; while the second has port2. I have printed (*) the local port of the connected Socket returned by serverSocket.accept() and all of them are the same as the one on which the serverSocket is listening. As long as all the clients are distinguishable there shouldn't be a problem. (*) Via Socket.getLocalPort() [ April 02, 2004: Message edited by: Jose Botella ]