Java 套接字 - ObjectInputStream
Java Socket - ObjectInputStream
我一直在 while 循环中使用语句 true 调用 ObjectInputStream:
while(true){
//send data
}
但是在关闭 Socket、ObjectInputStream 和其余部分时,我关闭了多个异常 Socket(实际上是因为我关闭了它)。
问题:我可以在 while 循环中放入什么语句来检查 ObjectInputStream 是否未关闭?
编辑:Socket.isConnected() 没有给出好的结果
整个方法
private void dataTransfer(){
try {
while(!con.isClosed()){
String message = (String) input.readObject();
ChatWindow.getMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
你的问题可能是多线程异步
虽然 while
在 EDT 之外运行,但 windowClosing()
在 EDT 内部运行。因此它可能会在实际调用 windowClosing()
之前检查 isClosed()
,然后执行循环代码。
与类似情况一样,最好的方法是使用同步,但这在 EDT 中并不是最好的主意。在关闭流并同步的 windowClosing()
方法中使用新线程。
我一直在 while 循环中使用语句 true 调用 ObjectInputStream:
while(true){
//send data
}
但是在关闭 Socket、ObjectInputStream 和其余部分时,我关闭了多个异常 Socket(实际上是因为我关闭了它)。
问题:我可以在 while 循环中放入什么语句来检查 ObjectInputStream 是否未关闭?
编辑:Socket.isConnected() 没有给出好的结果
整个方法
private void dataTransfer(){
try {
while(!con.isClosed()){
String message = (String) input.readObject();
ChatWindow.getMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
你的问题可能是多线程异步
虽然 while
在 EDT 之外运行,但 windowClosing()
在 EDT 内部运行。因此它可能会在实际调用 windowClosing()
之前检查 isClosed()
,然后执行循环代码。
与类似情况一样,最好的方法是使用同步,但这在 EDT 中并不是最好的主意。在关闭流并同步的 windowClosing()
方法中使用新线程。