Windows/Linux issue with Client/Server Socket with Applet

旧城冷巷雨未停 提交于 2020-01-04 13:26:12

问题


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


回答1:


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.




回答2:


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());
}


来源:https://stackoverflow.com/questions/23385949/windows-linux-issue-with-client-server-socket-with-applet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!