Search code examples
javasocketsserversocket

Properly disconnect client (telnet) from ServerSocket


I want a simple server socket to accept a client and read some texts and disconnect the client from itself. As a client I'm using a telnet for now, because in the future I will create a custom program.

    ServerSocket ss = new ServerSocket(SERVER_SOCKET_PORT); 
    Socket s = ss.accept();

    BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String line;
    while (true) {
        line = reader.readLine();
        if (line == null || line == "" || line == "q") {
            log("-- breaking the loop");
            break;
        }

        printf("**%s%n", line);
    }
    reader.close();
    s.close();
    ss.close();

The problem I'm having is the while loop never breaks.


Solution

  • First, that isn't how you compare String(s) for equality. Second, I would prefer String.isEmpty() to testing for equality with "". Finally, you can use a try-with-resources to close everything. Something like,

    try (ServerSocket ss = new ServerSocket(SERVER_SOCKET_PORT);
            Socket s = ss.accept();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(s.getInputStream()))) {
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.isEmpty() || line.equalsIgnoreCase("q")) {
                System.out.println("-- breaking the loop");
                break;
            }
    
            System.out.printf("**%s%n", line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }