问题描述
我是套接字编程和线程的新手.如果有人可以帮助我,我会很高兴.我目前正在处理多客户端服务器问题,其中每个新客户端连接都有自己的线程和小程序.这是断开连接时何时关闭客户端线程的代码片段.
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();
因此,当从 BufferedReader 读取空值时,它会退出 while 循环.我的问题是这在 linux 中完美运行.当 x 在小程序的角落被按下时,bufferedReader 得到一个空值并且线程优雅地终止.
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.
当我在 windows 中尝试这个时,我得到一个 SocketException: Connection reset
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)
windows 和 linux 在小程序关闭时是否做了不同的事情或者是我的代码
Does windows and linux do something different when the applet is closed or is it my code
推荐答案
Try with Scanner
并在得到 nextLine()
之前检查 hasNextLine()
>
Try with Scanner
and check hasNextLine()
before getting nextLine()
示例代码:
Scanner scanner = new Scanner(new InputStreamReader(socket.getInputStream()));
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
这篇关于带有 Applet 的客户端/服务器套接字的 Windows/Linux 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!