简体   繁体   English

捕获异常后如何正确关闭套接字?

[英]How to properly close a socket after an exception is caught?

After my last project I had the problem that the client was expecting an object from the server, but while processing the clients input an exception that forces the server to close the socket for security reasons is caught. 在我的上一个项目之后,我遇到了一个问题,即客户端期望服务器提供对象,但是在处理客户端时,输入了一个异常,该异常迫使服务器出于安全原因关闭套接字。

This causes the client to terminate in a very unpleasant way, the way I decided to deal with this was sending the client a Input status message after each recieved input so that he knows if his input was processed properly or if he needs to throw an exception. 这导致客户端以一种非常不愉快的方式终止,我决定处理此问题的方式是在每次接收到输入后向客户端发送输入状态消息,以便他知道自己的输入是否得到正确处理或是否需要抛出异常。

So my question: 所以我的问题是:

  • Is there a better/cleaner way to close the socket after an exception is caught? 捕获异常后,是否有更好/更清洁的方法来关闭套接字?

For things like this: 对于这样的事情:

  1. Make sure to put this socket code within a try/catch block. 确保将此套接字代码放入try / catch块中。
  2. Close the socket within a 'finally'. 最后“关闭”插座。 That way you ensure that you cleanly close the socket whether there is an exception or not. 这样,无论是否有异常,您都可以确保完全关闭套接字。

If I understand correctly you have already closed the socket from the server side, and you need your client to realize this and handle the error accordingly. 如果我理解正确,那么您已经从服务器端关闭了套接字,并且您需要客户端来实现这一点并相应地处理错误。

Take a look at the Socket documentation and in particular the setSoTimeout method. 看一下Socket文档,尤其是setSoTimeout方法。 For example, if the timeout is set to 5 seconds and the client attempts to read from the server socket and he does not get an answer, then the timeout expires and a java.net.SocketTimeoutException is raised and you can catch it and close the socket. 例如,如果超时设置为5秒,并且客户端尝试从服务器套接字读取并且他没有得到答案,则超时到期并且引发java.net.SocketTimeoutException ,您可以捕获它并关闭插座。

You could also use a ScheduledExecutorService or a Timer to simulate the timeout. 您还可以使用ScheduledExecutorServiceTimer来模拟超时。

Incorrect. 不正确 That exception only occurs when you try to use a socket you have closed yourself . 仅当您尝试使用已关闭的套接字时,才会发生该异常。

What the OP should be looking for is EOFException, or IOException: 'connection reset', or a SocketTimeoutException. OP应该寻找的是EOFException或IOException:“连接重置”或SocketTimeoutException。

You really can't since the socket is closed, you could listen on the client for 由于套接字已关闭,您确实不能,您可以在客户端上侦听

java.net.SocketException: socket closed 

and then you would know that you lost a connection to the server. 然后您会知道您失去了与服务器的连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM