Search code examples
javasocketssystem.exit

Ending Client Connection of Java Socket


I have a socket connection between a single client and server. I have implemented functions like login, logout, send, and make new user on the server side which then outputs different messages to the server and the client.

I need to implement a connection closing when the user uses the logout function while still having the server side running. I figured a System.exit(0) in the right place of the client side would be able to do it, but I'm having more trouble implementing it than I thought.

I attempted to put it where I think I'm getting the output back from the server, see the client side below, inside the while loop there is an if loop looking for the "logged out" response:

Client:

                if(ins.readLine().contains("Logged Out"))
                {
                     System.exit(0);
                }
                else
                {
                     System.out.println(ins.readLine());
                }

Without the if loop within the while loop of the client server everything works perfectly, however with the if loop there, it takes once command and then no longer prompts for commands, and keeps the connection open. Before it would continuously prompt the user for commands and keep the connection open.

Thoughts?


Solution

  • You read two lines instead of one. One here to check what you get from the server:

    if(ins.readLine().contains("Logged Out"))
    

    Another one to display what you get from the server:

    System.out.println(ins.readLine());
    

    To fix this, store the server response in a variable:

    String serverResponse = ins.readLine();
    if (serverResponse.contains("Logged Out")) {
      System.exit(0);
    } else {
      // reuse serverResponse instead of reading another line...
      System.out.println(serverResponse);  
    }