简体   繁体   中英

Close server and client socket connection at the same time

I have a created a client and server using sockets, Hangman game where the client sends the letter input to the server and so on. When the player wins or loses, the server terminates. I want the client to terminate at the same time as well before displaying "Enter letter: ". Is there a way of doing this?

Here is a part of my client code:

do {
        System.out.println();
        System.out.print("Enter letter: "); 
        BufferedReader UserIn = new BufferedReader(new InputStreamReader(System.in));
        input = UserIn.readLine();
        pw.println(input);
        System.out.println(SocketIn.readLine());
        System.out.println();

        while(SocketIn.ready()) {
            System.out.println(SocketIn.readLine());
        }   

    } while (socket.isConnected());

Get rid of the ready() test and recode your loop like this:

String line;
while ((line = SocketIn.readLine()) != null)
{
    System.out.println(line);
}

ready() can't tell you about end of stream. Neither does isConnected() .

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