client netty 主动发数据_netty发送和接收数据handler处理器

/*** netty服务器的监听 处理器

*

*@authorflm 2017年10月27日*/

public class IOHandler extendsChannelInboundHandlerAdapter {private static Logger log = Logger.getLogger(IOHandler.class);//netty AttributeKey 相对于 web session【重要】

public static final AttributeKey KEY = AttributeKey.valueOf("IO");privateProducer producer;publicIOHandler(Producer producer){this.producer=producer;

}/*** 读取数据*/@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throwsException {

DeviceSession session= ctx.channel().attr(KEY).get(); //检测是否 自己注册的 客户端

ByteBuf buffer=(ByteBuf) msg;if (buffer == null||session == null) {

closeConnection(ctx);//关闭连接

}

MsgEntity msgEntity= new MsgEntity(buffer); //解码 buffer 封装 msgEntity

log.info("# Accept Client data :"+msgEntity.toString());if (MsgType.UNKNOW ==msgEntity.getMsgType()) {

log.info("# 客户端 发送数据 类型未定义... :"+msgEntity.toString());return;

}if(!session.isActivity()){

session.setActivity(true);

session.setImei(msgEntity.getImei());

SessionManager.getSingleton().addClient(session);

}

producer.putData(msgEntity);

}/*** 客户端 注册*/@Overridepublic void channelRegistered(ChannelHandlerContext ctx) throwsException {super.channelRegistered(ctx);

log.info(String.format("# client registered...: %s ...", ctx.channel()));

DeviceSession session= newDeviceSession(ctx.channel());//绑定客户端到SOCKET

ctx.channel().attr(KEY).set(session);

}/*** 客户端 失去连接*/@Overridepublic void channelInactive(ChannelHandlerContext ctx) throwsException

{super.channelInactive(ctx);

log.info(String.format("# client out... : %s", ctx.channel()));

DeviceSession session= ctx.channel().attr(KEY).getAndSet(null);//移除 session 并删除 该客户端

SessionManager.getSingleton().removeClient(session, true);if(session.getDeviceID() != null)

{//producer.onData(new Request(new RootMessage(MessageType.LOGOUT, null, null), session));

}

}/*** 心跳机制 用户事件触发*/@Overridepublic void userEventTriggered(ChannelHandlerContext ctx, Object evt) throwsException

{if (evt instanceofIdleStateEvent)

{

IdleStateEvent e=(IdleStateEvent) evt;//检测 是否 这段时间没有和服务器联系

if (e.state() ==IdleState.ALL_IDLE)

{//检测心跳

checkIdle(ctx);

}

}super.userEventTriggered(ctx, evt);

}/*** 报错 处理事件*/@Overridepublic voidexceptionCaught(ChannelHandlerContext ctx, Throwable cause)throwsException {

log.error("# 客户端连接 Netty 出错...");

cause.printStackTrace();//关闭连接

closeConnection(ctx);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,我们需要在Spring Boot项目中引入Netty的依赖: ``` <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.22.Final</version> </dependency> ``` 然后,我们需要编写一个Netty客户端类,用于连接服务器并发送16进制数据: ```java public class NettyClient { private final String host; private final int port; private Channel channel; public NettyClient(String host, int port) { this.host = host; this.port = port; } public void connect() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HexEncoder()); pipeline.addLast(new NettyClientHandler()); } }); ChannelFuture future = bootstrap.connect(host, port).sync(); channel = future.channel(); channel.closeFuture().sync(); } finally { group.shutdownGracefully(); } } public void sendHexData(String hexData) { if (channel == null || !channel.isActive()) { throw new IllegalStateException("Connection is not active"); } channel.writeAndFlush(Unpooled.copiedBuffer(hexData, CharsetUtil.US_ASCII)); } } ``` 在上面的代码中,我们使用了HexEncoder类来将字符串转换为16进制数据,然后将它们发送到服务器。我们还使用了NettyClientHandler类来处理从服务器接收到的响应。 最后,我们可以在Spring Boot应用程序中使用这个Netty客户端类来发送16进制数据: ```java @RestController @RequestMapping("/api") public class NettyController { @GetMapping("/sendHexData") public String sendHexData(@RequestParam String hexData) throws Exception { NettyClient client = new NettyClient("localhost", 8080); client.connect(); client.sendHexData(hexData); return "OK"; } } ``` 在上面的代码中,我们可以使用sendHexData方法来发送16进制数据到服务器。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值