问题描述
当我 flush()
来自服务器的 OutputStream
的消息时,客户端是否收到消息(如果它在超时之前断开连接)。我需要以某种方式从服务器端控制这种情况,我必须知道客户端是否能够在发送之前接收消息。如何做到这一点?
When I flush()
the message from the server's OutputStream
, the client either received message or not (if it was disconnected before timeout). I need to somehow control this situation from server-side, I have to know if client is able to receive the message before sending it. How it could be done?
推荐答案
过去,我通常在一个单独的线程中使用阻塞读取来读取客户端消息并根据需要传播它们。
In the past, I have typically used a blocking read in a separate thread to read client messages and disseminate them as needed.
如果客户端断开连接,操作返回-1,我们将其视为客户端已断开连接并且应关闭InputStream的通知。如果连接异常终止,它也可能抛出IOException。
If the client disconnects, the InputStream.read() operation returns -1 and we take that as notification that the client has "disconnected" and the InputStream should be closed. It may also throw an IOException if the connection is abnormally terminated.
然后你可以测试以验证您是否仍然可以写信息。
You can then test Socket.isClosed() to verify whether or not you can still write messages.
这篇关于Java套接字:检查客户端是否能够从服务器接收消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!