开发者

Is calling ServerSocket.close() sufficient enough to close a port?

I have some java code that looks similar to this:

private void startServer() throws IOException {
        URLClassLoader classloader = null;

        System.out.println("Opening se开发者_运维技巧rver socket for listening on " + PORT_NUMBER);
        try {
            server = new ServerSocket(PORT_NUMBER);
            server.setSoTimeout(10000);
            connected = true;
            System.out.println("Server is now listening on port " + PORT_NUMBER);
        } catch (IOException e) {
            System.err.println("Could not start server on port " + PORT_NUMBER);
            e.printStackTrace();
            connected = false;
        }

        while (connected) {

            // Incoming request handler socket.
            Socket socket = null;
            try {
                System.out.println("Waiting for client connection...");
                // Block waiting for an incoming connection.
                socket = server.accept();
                if (socket == null) continue;

...and so on and so forth. When I call server.close() later on (I don't get any different behavior if I call socket.close() first), I don't get any errors, but netstat shows that the port is still being listened on. Should calling ServerSocket.close() be sufficient enough to free up the port on this system?

I am programming for a Java 1.4.2 microedition runtime. It is also worthy to note that I have this method being run in another thread, and I am trying to close the socket from its parent thread.

EDIT Here is the line from netstat, though I can assure you it is still being listened on, since if I start the Xlet again I get an exception with that port number.

tcp        0      0  *.2349                 *.*                    LISTEN


There are several things to consider. One of them is described by the following quotation from JavaDoc of ServerSocket

public void setReuseAddress(boolean on) throws SocketException

Enable/disable the SO_REUSEADDR socket option. When a TCP connection is closed the connection may remain in a timeout state for a period of time after the connection is closed (typically known as the TIME_WAIT state or 2MSL wait state). For applications using a well known socket address or port it may not be possible to bind a socket to the required SocketAddress if there is a connection in the timeout state involving the socket address or port.

So it is kind of OK that the OS can still show that there is something going on after you close() the server socket. But if you going to open/close a server socket on the same port frequently you might hit a problem.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜