这个问题说明了一切;使用“.close()”方法而不是仅仅将套接字设置为空会更好吗?但是“.close()”方法不能抛出异常,那个时候我可以直接设置为null吗?
一旦我关闭了一个套接字,只要安全措施在我调用“.close()”后将套接字设置为空,我可以用不同的连接再次重用同一个套接字吗?还是我需要重新创建一个全新的套接字。
这个问题说明了一切;使用“.close()”方法而不是仅仅将套接字设置为空会更好吗?但是“.close()”方法不能抛出异常,那个时候我可以直接设置为null吗?
一旦我关闭了一个套接字,只要安全措施在我调用“.close()”后将套接字设置为空,我可以用不同的连接再次重用同一个套接字吗?还是我需要重新创建一个全新的套接字。
The question is meaningless. Setting a variable to null does nothing to the socket, except possibly make it eligible for GC. If you want to close a socket, close it, or better still close the outermost output stream or writer you have wrapped around its output stream. The fact that this can throw an exception mustn't deter you.
But cant the ".close()" method throw an exception
It may, so wrap close() also in try/catch. If close() fails, that's ok you tried failed, make it null
and continue.
And once I close a socket, just safe measures set the socket to null after I call ".close()", can I reuse that same socket again with a different connection? Or do I need to recreate a whole new socket.
Closing socket will also close the socket's InputStream and OutputStream. Once a socket has been closed, it is not available for further networking use (i.e. can't be reconnected or rebound). A new socket needs to be created.
是的,最好在将套接字设置为空之前关闭套接字。我会说在调用 close 后将其设置为 null 是安全的,无论它是否引发异常。如果在关闭它之前将其设置为 null,则套接字将仍然存在并占用端口,直到它在稍后的某个未知时间被 jvm 销毁。
是的,您必须在关闭它后创建一个新套接字。