[英]SocketException when closing socket
我有一個客戶端,它連續發送和接收數據消息,工作正常,但是當我關閉/停止客戶端時,我收到以下單行錯誤:
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();
}
}
我認為即使在您的主線程關閉套接字后,您仍在嘗試從單獨線程中的套接字讀取,另一個線程仍在嘗試從中讀取。
我想一個簡單的簽入你的另一個線程可能會解決這個問題:
if(socket.isClosed())
System.out.println(in.readLine());
我對isClosed
的使用持懷疑態度,但我認為值得一試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.