我用 Java 创建了一个 TCP Web 套接字客户端并将其连接到远程 TCP 服务器。在正常情况下,它工作正常。
我需要检测套接字断开连接并在断开连接触发后处理一些逻辑。我计划通过在套接字客户端写入其输出流以发送消息时捕获异常来检测断开连接。
但是,当我关闭 wifi 连接或移除套接字客户端的 LAN 电缆时,它不会在几秒钟内识别出与服务器的断开连接。客户端识别与服务器断开连接并在读取时抛出以下异常需要不同的时间段(秒或分钟)。
java.net.SocketTimeoutException: 读取超时。
我担心的是在套接字客户端抛出上述异常之前的断开连接期间,它成功地将消息写入他的输出流并且不会抛出任何套接字异常。因此,我的一些消息丢失了。
下面是我的示例套接字客户端的实现来测试场景 (Java)。
创建套接字连接
public void connect(String ipAddress, int port) throws MxLightAgentException {
try {
if (socket != null) {
socket.close();
}
SocketAddress socketAddress = new InetSocketAddress(ipAddress, port);
socket = new Socket();
socket.connect(socketAddress, 20000);
socket.setKeepAlive(true);
setupSSL(ipAddress, port);
} catch (IOException ex) {
throw new MxLightAgentException
("Error when creating socket connection. IP: " + ipAddress + " Port: " + port, ex);
}
}
断开套接字连接
public void disconnect() {
if (socket != null) {
try {
output.close();
incommingMessageProcessor.stopThread();
socket.close();
} catch (IOException e) {
LOGGER.info("disconnect", "Error on disconnection", e);
}
}
}
写入输出流
public boolean sendMessage(byte[] message) throws MxLightAgentException {
try {
LOGGER.info("Sending message via socket");
output = this.socket.getOutputStream();
byte[] len = DataConverter.toBytes(message.length);
output.write(len);
output.write(message);
output.flush();
LOGGER.info("Message sent and flushed");
return true;
} catch (IOException ex) {
throw new MxLightAgentException("Error when sending message to proxy.", ex);
}
}
我也实现了一个 Netty 套接字客户端并得到了相同的结果。
即使网络连接断开,写入输出流时也不会抛出任何异常的原因是什么?
aluckdog
翻阅古今
相关分类