【发布时间】:2021-12-10 04:26:32
【问题描述】:
我有一个客户端,它连续发送和接收数据消息,它工作正常,但是当我关闭/停止客户端时,我收到以下单行错误:
java.net.SocketException: 套接字关闭
尽管我在 try-finally 封闭中关闭了套接字。现在我的问题是为什么我会收到这个错误,这种行为是否正常以及如何正确处理这个错误。以下是我的代码:
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = null;
try {
socket = new Socket("localhost", 9101);
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
try {
System.out.println(in.readLine());
} catch (IOException e) {
e.printStackTrace();
System.out.println("error");
}
}
}
});
thread.start();
System.out.println("Write to server:");
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String message = scanner.nextLine();
out.println(message);
out.flush();
};
} finally {
socket.close();
}
}
【问题讨论】:
-
您需要为该异常提供更多上下文。该异常来自代码中的哪一行?
标签: java sockets networking tcp