Windows/Linux issue with Client/Server Socket with

2019-07-14 03:57发布

I'm new at socket programming and threads. I'd be happy if anyone can help me out. I currently working on a multi-client server problem where each new client connection gets its own thread and its an applet. here is a code snippet of when to close the thread of a client when it disconnects.

   String inputMessage; //message stored here
   BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream()));
   while((inputMessage = in.readLine()) != null){
            //Update message buffer with message that client has typed 
            buffer.insertMessage(inputMessage);

    }
    // Close things
        in.close();
        socket.close();

So when a null is read from the BufferedReader, it exits the while loop. My issue is this works perfectly in linux. When x is pressed in the corner of the applet, the bufferedReader gets a null and the thread terminates gracefully.

When I tried this in windows, I get a SocketException: Connection reset

    java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
    at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
    at sun.nio.cs.StreamDecoder.read(Unknown Source)
    at java.io.InputStreamReader.read(Unknown Source)
    at java.io.BufferedReader.fill(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)

Does windows and linux do something different when the applet is closed or is it my code

2条回答
Anthone
2楼-- · 2019-07-14 04:15

Try with Scanner and check hasNextLine() before getting nextLine()

sample code:

Scanner scanner = new Scanner(new InputStreamReader(socket.getInputStream()));
while (scanner.hasNextLine()) {
    System.out.println(scanner.nextLine());
}
查看更多
Fickle 薄情
3楼-- · 2019-07-14 04:34

Either you have written to an connection that had already been closed by the peer, or the peer has exited without closing the socket at all.

查看更多
登录 后发表回答