开发者

Java Socket and ServerSocket Issue

I have this code snippet:

ServerSocket serversocket=new ServerSocket(DEFAULTPORT);
serversocket.setSoTimeout(1000);
Socket socket=serversocket.accept();
  1. Does closing the serversocket object also affe开发者_开发问答cts the state of the socket object?

  2. If I close the serversocket object can I still use the socket 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜