aspose file tools*
The moose likes Sockets and Internet Protocols and the fly likes Why should I use a new Socket to interrupt serverSocket.accept() ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "Why should I use a new Socket to interrupt serverSocket.accept() ?" Watch "Why should I use a new Socket to interrupt serverSocket.accept() ?" New topic
Author

Why should I use a new Socket to interrupt serverSocket.accept() ?

Leon Omk
Ranch Hand

Joined: Aug 17, 2010
Posts: 75



I want to shutdown server elegantly. In the code, serverSocket.accept() will be listening at the endpoint forever.

Approach 1, servletSocket.close() will case serverSocket.accept() to throw exception. Ugly, since my isGoingToShutdown flag is completely useless.

Approach 2, use "new Socket(serverSocket.getInetAddress(), serverSocket.getLocalPort()).close();" to interrupt serverSocket.accept(). Works. But why, why it works, and why should I do it in this way?


OK, so that other guy knows Java better than I do, but I bet he can't speak Wuhanese(a Chinese Dialect) like me.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19783
    
  20

It's just how the accept() method works. It blocks until a connection is made. If that's not good for you you should check out NIO and java.nio.channels.Selector. This will poll until there is actually activity; a connection request, data, etc. This polling can have a timeout so you won't have to wait indefinitely.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Leon Omk
Ranch Hand

Joined: Aug 17, 2010
Posts: 75

I'm curious about interrupting accept(). If accept() is invoked, a ServerSocket is listening at the endpoint(local server address+port).

If we close this ServerSocket directly, accept() would be interrupted and an exception would be thrown, saying "socket closed".

But if we create a new socket(not serverSocket) on the same endpoint, then close it. The serverSocket.accept() will stop silently without any exception thrown! Why is there no exception?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19783
    
  20

The new socket connection will cause accept() to not wait any longer, and return the other side of the connection. Since you abort the loop immediately and the server doesn't do anything with the socket there is no code that can throw an exception. Only if you call any methods on the closed socket will an exception be thrown.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why should I use a new Socket to interrupt serverSocket.accept() ?