5

I have this code snippet:

ServerSocket serversocket=new ServerSocket(DEFAULTPORT);
serversocket.setSoTimeout(1000);
Socket socket=serversocket.accept();
  1. Does closing the serversocket object also affects the state of the socket object?

  2. If I close the serversocket object can I still use the socket object for my streams?

1
  • huh? what does it has to do with my question? Commented Feb 23, 2011 at 15:34

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

super thanks! the codes was just for clarification so that readers can understand what i meant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.