ModbusRtuMasterWithTcpServerHandler.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package com.jiayue.ipfcst.client.protocol2file;
  2. import io.netty.buffer.ByteBuf;
  3. import io.netty.channel.ChannelHandlerContext;
  4. import io.netty.channel.SimpleChannelInboundHandler;
  5. import org.slf4j.Logger;
  6. import wei.yigulu.modbus.netty.ModbusMasterBuilderInterface;
  7. import wei.yigulu.utils.DataConvertor;
  8. import java.net.InetSocketAddress;
  9. /**
  10. * 以TCPserver的通讯方式 传输RTU协议 Master角色 处理器
  11. * @author: xiuwei
  12. * @version:
  13. */
  14. public class ModbusRtuMasterWithTcpServerHandler extends SimpleChannelInboundHandler<ByteBuf> {
  15. protected Logger log;
  16. /**
  17. * Slave 104 handle
  18. *
  19. * @param builder slaver builder
  20. */
  21. public ModbusRtuMasterWithTcpServerHandler(ModbusRtuMasterWithTcpServer builder) {
  22. this.builder = builder;
  23. this.log = builder.getLog();
  24. }
  25. protected ModbusRtuMasterWithTcpServer builder;
  26. @Override
  27. public void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
  28. //收数据
  29. log.info("re <== " + DataConvertor.ByteBuf2String(byteBuf));
  30. ((ModbusMasterBuilderInterface) this.builder).getOrCreateSynchronousWaitingRoom().setData(byteBuf.nioBuffer());
  31. }
  32. @Override
  33. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  34. log.error("ModbusSlave交互时发生异常", cause);
  35. }
  36. @Override
  37. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  38. InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
  39. String clientIp = ipSocket.getAddress().getHostAddress();
  40. Integer clientPort = ipSocket.getPort();
  41. if (!this.builder.getConnectFilterManager().verdict(ctx.channel())) {
  42. ctx.channel().close();
  43. log.info(clientIp + ":" + clientPort + "客户端被过滤链拦截,已关闭通道");
  44. return;
  45. }
  46. log.info(clientIp + ":" + clientPort + "客户端连接");
  47. this.builder.connected(ipSocket);
  48. this.builder.getChannels().add(ctx.channel());
  49. }
  50. @Override
  51. public void channelInactive(ChannelHandlerContext ctx) throws Exception {
  52. InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
  53. String clientIp = ipSocket.getAddress().getHostAddress();
  54. Integer clientPort = ipSocket.getPort();
  55. log.info(clientIp + ":" + clientPort + "客户端断开连接");
  56. this.builder.getChannels().remove(ctx.channel());
  57. this.builder.disconnected(ipSocket);
  58. }
  59. }