Spacewalker
Spacewalker

Reputation: 571

Close socket and release ressources

I try to write a simple chat software. But I am new socket programming and therefore I have a question:

When a chat client sends "goodby" to the server the server should close the client's connection and release all ressources. But after I close the socket the "isConnected()" flag still shows "true".

I have found some threads with similar questions but I must admit that I don't understood all the explainations there.

But is seems that socket.isConnected() does not show the current connection state of a a socket ?

Is this right?

So how can the server close a client connection (socket) and release all ressources etc. back to the operating system?

I want to avoid that over time the server will keep "dead" connections\sockets.

Is it enough to just execute "socket.close" ?

My Server code:

class connection extends Thread
{
        public  Socket           client;
        public  PrintStream      output;    
        private BufferedReader   input;    

...
...

while(true)         //loop where server waits for client's message
{

    //****** wait for client's message
    line=input.readLine();

    //******* Client wants to leave chat  - so close its connection , release server ressources, close this thread...
    if (line.equals("goodbye"))    
        {
            //close I/O streams
            this.input.close();
            this.output.flush();
            this.output.close();  

            //Close Socket
            client.close();     //<-- results in: .isClosed()==true  but : .isConnected()==true

            //close thread (not clear if neccessary)
            this.stop(); 

            //exit loop / this should also exit and thus close this thread
            break;
    }
}

Upvotes: 0

Views: 737

Answers (2)

user207421
user207421

Reputation: 311039

Is it enough to just execute "socket.close" ?

Yes. Normally however you will close the outermost OutputStream or Writer you have wrapped around the socket output stream. That will flush it, close the stream, close the input stream, and close the socket.

Upvotes: 1

AJ.
AJ.

Reputation: 4534

According to Java Docs

public boolean isConnected()

Returns the connection state of the socket.

Note: Closing a socket doesn't clear its connection state, which means this method will return true for a closed socket (see isClosed()) if it was successfuly connected prior to being closed.

Upvotes: 2

Related Questions