你如何处理Java中的Socket Disconnecting? [英] How do you handle Socket Disconnecting in Java?
问题描述
我希望能够检测并处理断开连接,然后在必要时重新连接新客户端。
检测客户端断开连接,关闭套接字,然后接受新客户端的正确步骤是什么?
据推测,你是从套接字读取,可能使用输入流上的包装器,例如BufferedReader。在这种情况下,当相应的读操作返回-1(对于原始read()调用)或null(对于readLine()调用)时,可以检测到流结束。
某些操作在关闭的套接字上执行时会导致SocketException,您还需要适当处理。
Hey all. I have a server written in java using the ServerSocket and Socket classes.
I want to be able to detect and handle disconnects, and then reconnect a new client if necessary.
What is the proper procedure to detect client disconnections, close the socket, and then accept new clients?
Presumably, you're reading from the socket, perhaps using a wrapper over the input stream, such as a BufferedReader. In this case, you can detect the end-of-stream when the corresponding read operation returns -1 (for raw read() calls), or null (for readLine() calls).
Certain operations will cause a SocketException when performed on a closed socket, which you will also need to deal with appropriately.
这篇关于你如何处理Java中的Socket Disconnecting?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!