ServerHandler.java 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package com.zksy.environmentHJ212.config;
  2. import com.zksy.environmentHJ212.utils.MonitorDatasynch;
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.buffer.Unpooled;
  5. import io.netty.channel.ChannelHandlerContext;
  6. import io.netty.channel.ChannelInboundHandlerAdapter;
  7. import io.netty.util.ReferenceCountUtil;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.stereotype.Component;
  11. import javax.annotation.PostConstruct;
  12. import java.time.LocalDateTime;
  13. @Slf4j
  14. @Component
  15. public class ServerHandler extends ChannelInboundHandlerAdapter {
  16. private static ServerHandler serverHandler;
  17. @Autowired
  18. private MonitorDatasynch monitorDatasynch;
  19. @PostConstruct
  20. public void init() {
  21. log.info("init()方法");
  22. serverHandler = this;
  23. serverHandler.monitorDatasynch = this.monitorDatasynch;
  24. }
  25. /**
  26. * 客户端与服务端创建连接的时候调用
  27. */
  28. @Override
  29. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  30. log.info("客户端与服务端连接开始...");
  31. NettyConfig.group.add(ctx.channel());
  32. // 往客户端发送消息的代码(注释部分)若启用,也需注意ByteBuf释放
  33. }
  34. /**
  35. * 客户端与服务端断开连接时调用
  36. */
  37. @Override
  38. public void channelInactive(ChannelHandlerContext ctx) throws Exception {
  39. log.info("客户端与服务端连接关闭...");
  40. NettyConfig.group.remove(ctx.channel());
  41. }
  42. /**
  43. * 服务端接收客户端发送过来的数据结束之后调用
  44. */
  45. @Override
  46. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  47. ctx.flush();
  48. log.info("信息接收完毕...");
  49. }
  50. /**
  51. * 工程出现异常的时候调用
  52. */
  53. @Override
  54. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  55. log.error("发生异常", cause);
  56. ctx.close();
  57. }
  58. /**
  59. * 服务端处理客户端请求的核心方法
  60. */
  61. @Override
  62. public void channelRead(ChannelHandlerContext channelHandlerContext, Object info) throws Exception {
  63. try {
  64. ByteBuf buf = (ByteBuf) info;
  65. byte[] req = new byte[buf.readableBytes()];
  66. buf.readBytes(req);
  67. String msg = new String(req);
  68. log.info("接收数据: {}, 时间: {}", msg, LocalDateTime.now());
  69. // 调用业务方法处理数据
  70. String pushMonitorDataStr = serverHandler.monitorDatasynch.pushMonitorData(channelHandlerContext, msg);
  71. } catch (Exception e) {
  72. log.error("数据处理错误", e);
  73. } finally {
  74. ReferenceCountUtil.release(info);
  75. channelHandlerContext.flush();
  76. }
  77. }
  78. }