简体   繁体   中英

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.

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();
}
while (true) {
    line = reader.readLine();
    if (line == null || line == "" || line == "q") {

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

So the peer never

  • closes the connection
  • sends an empty line that compares to "" via the (incorrectly applied) == operator
  • sends a string consisting only of "q" plus a line terminator.

The normal way to write this loop would be:

while ((line = reader.readLine()) != null)
{
    if (line.isEmpty() || line == "q") {
        log("-- breaking the loop");
        break;
    }

    printf("**%s%n", line);
}

But if the peer never closes the connection or sends the "q" there's no way this loop will ever exit. Are you sending anything that would produce either of those conditions?

disconnect the client from itself

This is meaningless. Please restate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM