[英]Java socket read timeout exceptions
I try to overcome a user disconnection detection on the server side using read timeout. 我尝试使用读取超时来克服服务器端的用户断开连接检测。 This is part of my code:
这是我的代码的一部分:
try {
socket.setSoTimeout(3000);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
usr = new User(in.readUTF());
usr.connectUser();
int i=0;
while(true){
try{
i = in.readInt();
}
catch(SocketTimeoutException e){
System.Out.Println("Timeout");
// user connected, no data received
}
catch(EOFException e){
System.Out.Println("Disconnected");
// user disconnected
}
}
}
catch(Exception e){
// other exceptions
}
the code works fine except the "user disconnected" issue. 该代码工作正常,除了“用户断开连接”问题。 i want to catch the timeout exception and just continue waiting for data but only if the client still connected.
我想捕获超时异常,只是继续等待数据,但前提是客户端仍然连接。 why i never get other exception than SocketTimeoutException?
为什么我再也没有收到SocketTimeoutException以外的异常? shouldn't i get IOException while in.readInt() can't use the socket because client disconnected?
在in.readInt()不能使用套接字的情况下,由于客户端断开连接,我是否应该获得IOException?
is there any other simple way to detect user disconnection? 还有其他简单的方法可以检测用户断开连接吗? i mean as unwanted disconnection, like user had suddenly wifi shutdown etc...
我的意思是不想要的断开连接,例如用户突然关闭了wifi等...
thanks, Lioz. 谢谢,利兹。
If the client didn't write anything within the timeout period, you get a SocketTimeoutException. 如果客户端在超时时间内未写入任何内容,则会收到SocketTimeoutException。 If he disconnected instead of writing anything, you get an EOFException.
如果他断开连接而不是写任何东西,则会得到EOFException。 Catch them separately.
分别捕获它们。 If you didn't get an EOFException, he didn't disconnect.
如果您没有收到EOFException,则他不会断开连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.