我正在创建一个NetUtils类,该类扩展线程以处理GUI中的套接字通信而不会阻塞主线程。我的代码如下所示(假设所有导入都被考虑在内):
主要方法
public static void main(String[] args) {
EventQueue.invokeLater( () -> {
new Window().setVisible(true);
});
}
窗口类
public class Window { // normally would extend JFrame bc this is a gui
// ...
NetUtils comms;
public Window() {
// ...
comms = new NetUtils("192.168.1.1", 288); // this ip/port info works fine
comms.start();
// ...
}
// other methods....
}
NetUtils类
public class NetUtils extends Thread {
private String ip;
private int port;
public NetUtils(String ip, int port) {
this.ip = ip;
this.port = port;
}
@Override
public void run() {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(ip, port), 10000); // timeout 10s
System.out.println("Socket started: " + socket); // correctly prints
while (true) { // during the life of the thread
String line = readLine(socket); // throws SocketException here (socket closed error)
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private String readLine(Socket socket) {
// uses inputstream to read bytes and such
String line;
boolean isDone = false;
while (!isDone) {
try (InputStreamReader isr = new InputStreamReader(socket.getInputStream))) {
if (isr.ready()) {
line += (char) isr.read();
}
if (!isr.ready() && line != "") {
isDone = true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return line;
}
}
我在做什么会导致套接字关闭?我直接在main方法中运行NetUtils代码(我没有将readLine方法分开),它按照我的预期运行,这让我相信问题与套接字在线程中有关。谢谢你的帮助。
答案 0 :(得分:0)
显然'这部分有效'正在关闭套接字或其输入或输出流。
注意:您没有在发布的代码中检查流的结尾。我不认为需要readLine()
方法。只需用以下代码替换你的循环:
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
reader.close();
[省略异常处理。]