[英]How to catch a socket-timeout in Java
I'm writing a server with Java.net.我正在用 Java.net 编写服务器。 Now i want to change some variables on socket-timeout.
现在我想更改套接字超时的一些变量。
I cant find a 'onTimeout' interface or something similar.我找不到“onTimeout”界面或类似的东西。
Now I'm searching for a solution for this problem.现在我正在寻找解决这个问题的方法。
You say you're using java.net
so I'm assuming that you're using something like a java.net.ServerSocket
.您说您使用的是
java.net
,所以我假设您使用的是java.net.ServerSocket
之类的东西。 If you call setSoTimeout on your instance of ServerSocket
, you will be able to set a timeout for your socket.如果您在
ServerSocket
实例上调用setSoTimeout ,您将能够为您的套接字设置超时。 Then, when you block during calls to accept , your ServerSocket
will keep track of the timeout.然后,当您在调用accept期间阻塞时,您的
ServerSocket
将跟踪超时。 As you can see in the documentation, accept throws a SocketTimeoutException
if a timeout has been defined and the wait time has exceeded the timeout.正如您在文档中看到的,如果已定义超时并且等待时间已超过超时,则接受会抛出
SocketTimeoutException
。 So, you'll end up with something like this (forgive me for being a bit rusty on Socket
s):所以,你最终会得到这样的结果(请原谅我对
Socket
有点生疏):
try(ServerSocket ssock = new ServerSocket(...))
{
ssock.setSoTimeout(10_000); // 10 second timeout
while(true)
{
Socket csock = ssock.accept();
methodToStartThreadThatHandlesClientSocket(csock);
}
}
catch(SocketTimeoutException ste)
{
//handle socket timeout
}
catch(Exception other)
{
//handle other exceptions
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.