在 Java 中检查 DatagramSocket() 的 setSoTimeout

发布于 2024-09-24 22:15:35 字数 262 浏览 1 评论 0原文

我对java相当陌生,我有一个可能很容易回答的问题。

我有一个 DatagramSocket,并且我已将 setSoTimeout 设置为 2 秒左右。我从Java库中知道,如果向该套接字发出recieve()并且2秒过去了并且它没有收到回复,则会引发异常(java.net.SocketTimeoutException)。现在对我来说,当引发此异常时,我的整个客户端都会关闭。我需要一种方法来查看是否发生了此异常并移至代码的另一部分,而不是关闭整个客户端。

预先感谢您的帮助。

I'm fairly new to java and I have a, probably, very easy question to answer.

I have a DatagramSocket and i have set the setSoTimeout to be around 2 seconds. I know from the Java library that if a recieve() is issued to this socket and 2 seconds passes and it doesn't recieve a reply, an exception is raised (java.net.SocketTimeoutException). Now for me, when this exception is raised, my entire client shuts down. I need a way to see if this exception has occurred and move to another section of my code rather than closing the entire client.

Thanks in advance for your help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倾城花音 2024-10-01 22:15:35

将抛出 java.net.SocketTimeoutException 的行用 try/catch 块包裹起来。

try {
  socket.receive(p);
} catch (SocketTimeoutException ste) {
  ste.printStackTrace();
}

Wrap the line that throws java.net.SocketTimeoutException with try/catch block.

try {
  socket.receive(p);
} catch (SocketTimeoutException ste) {
  ste.printStackTrace();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文