package com.ruoyi.dataInterchange.netty.client;
|
|
import io.netty.buffer.ByteBuf;
|
import io.netty.buffer.Unpooled;
|
import io.netty.channel.ChannelHandlerContext;
|
import io.netty.channel.ChannelInboundHandlerAdapter;
|
import io.netty.util.CharsetUtil;
|
|
import java.util.ArrayList;
|
import java.util.List;
|
|
/**
|
* @author zhibing.pu
|
* @Date 2025/3/3 20:13
|
*/
|
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
|
|
public static List<ChannelHandlerContext> cts = new ArrayList<ChannelHandlerContext>();
|
|
|
/**
|
* 向服务端发送数据
|
*/
|
@Override
|
public void channelActive(ChannelHandlerContext ctx) throws Exception {
|
System.err.println("客户端和服务端已建立连接");
|
}
|
|
public void write(ChannelHandlerContext ctx , String mess) throws Exception {
|
String sendInfo = mess;
|
ctx.writeAndFlush(Unpooled.copiedBuffer(sendInfo, CharsetUtil.UTF_8)); // 必须有flush
|
ctx.flush();
|
}
|
|
@Override
|
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
|
//读取数据
|
|
//读取数据
|
ByteBuf buf1 = (ByteBuf) msg;
|
byte[] req = readClientData((ByteBuf) msg);
|
String body = new String(req, "UTF-8"); //获取到的值
|
System.out.println("客户端的数据------>"+body);
|
//写数据
|
write(ctx,"wits写的数据");
|
|
}
|
|
//将netty的数据装换为字节数组
|
private byte[] readClientData(ByteBuf msg) {
|
ByteBuf buf = msg;
|
byte[] req = new byte[buf.readableBytes()];
|
buf.readBytes(req);
|
buf.release();
|
return req;
|
}
|
|
/**
|
* channelInactive
|
* channel 通道 Inactive 不活跃的
|
* 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
|
*/
|
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
|
System.out.println("客户端与服务端通道-关闭:" + ctx.channel().localAddress() + "channelInactive");
|
}
|
|
@Override
|
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
|
cts.remove(ctx);
|
ctx.close();
|
System.out.println("异常退出:" + cause.getMessage());
|
}
|
}
|