Java Socket and ServerSocket Issue
I have this code snippet:
ServerSocket serversocket=new ServerSocket(DEFAULTPORT);
serversocket.setSoTimeout(1000);
Socket socket=serversocket.accept();
Does closing the
serversocket
object also affe开发者_开发问答cts the state of thesocket
object?If I close the
serversocket
object can I still use thesocket
object for my streams?
The short answers are:
1) no
2) yes
The longer answer is:
The ServerSocket waits for clients to connect (he waits in his accept-method). When there is a client, the accept-method returns, more specifically it returns a Socket-object which then represents the server's endpoint of the server-client connection. If the server closes his server-socket, he no longer listens (he no longer accepts new clients) but the clients with which he already has a socket-connection are unaffected.
Your code is not "wrong" per se, however it is only capable of accepting a single client and only if it connected within 1000 milliseconds.
Here is an introduction including sample code:
http://download.oracle.com/javase/tutorial/networking/sockets/clientServer.html
精彩评论