Files
SIPAIIS_WMS_JSSW/src/main/java/com/sipai/netty/NettyClientHandler.java

108 lines
3.5 KiB
Java

package com.sipai.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Date;
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
private NettyClient nettyClient;
public NettyClientHandler(NettyClient nettyClient) {
this.nettyClient = nettyClient;
}
/**
* 通道信息读取处理
* @param ctx
* @param msg
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf m = (ByteBuf) msg; // 将消息转化成bytebuf
try {
System.out.println("客户端直接打印接收到的消息: " + m.toString(Charset.defaultCharset()));
long currentTimeMillis = (m.readUnsignedInt() - 2208988800L) * 1000L;
System.out.println(new Date(currentTimeMillis));
/**
* 给服务端回复消息
*/
ctx.writeAndFlush("客户端收到! 消息为: " + m.toString(Charset.defaultCharset()));
} catch (Exception e) {
System.err.println("读取消息异常: " + e.getMessage());
} finally {
m.release();
}
}
/**
* 连接成功后,自动执行该方法
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
/**
* 往服务端发送消息
* 消息格式必须是ByteBuf才行!!!!!
* 如果是其他格式服务端是接收不到的!!!!
*/
System.out.println("首次连接完成!");
String helo = "你好呀!";
ByteBuf byteBuf = Unpooled.wrappedBuffer(helo.getBytes());
ctx.channel().writeAndFlush(byteBuf);
}
/**
* 当连接断开时调用
* @param ctx
* @throws Exception
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("连接已断开,准备重连...");
if (nettyClient != null) {
nettyClient.reconnect();
}
}
/**
* 异常处理
* @param ctx
* @param cause
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// 处理远程主机强制关闭连接的异常
if (cause instanceof IOException) {
String message = cause.getMessage();
if (message != null && (message.contains("远程主机强迫关闭了一个现有的连接")
|| message.contains("Connection reset")
|| message.contains("远程主机强迫关闭")
|| message.contains("An existing connection was forcibly closed"))) {
System.out.println("[" + java.time.LocalDateTime.now() + "] 远程主机已关闭连接,等待重连...");
ctx.close();
// 触发重连
if (nettyClient != null) {
nettyClient.reconnect();
}
return;
}
}
// 其他异常只打印简要信息,不打印完整堆栈
System.err.println("[" + java.time.LocalDateTime.now() + "] 客户端异常:" + cause.getClass().getSimpleName() + " - " + cause.getMessage());
ctx.close();
// 触发重连
if (nettyClient != null) {
nettyClient.reconnect();
}
}
}