WeightServerHandler.java 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package com.huimv.weight.server;
  2. import com.huimv.weight.service.IWeight;
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.buffer.Unpooled;
  5. import io.netty.channel.ChannelFutureListener;
  6. import io.netty.channel.ChannelHandler.Sharable;
  7. import io.netty.channel.ChannelHandlerContext;
  8. import io.netty.channel.ChannelInboundHandlerAdapter;
  9. import io.netty.util.CharsetUtil;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.stereotype.Component;
  12. /**
  13. * @Project : huimv.shiwan
  14. * @Package : com.huimv.biosafety.uface.controller
  15. * @Description : TODO
  16. * @Version : 1.0
  17. * @Author : ZhuoNing
  18. * @Create : 2020-12-25
  19. **/
  20. @Sharable
  21. @Component
  22. public class WeightServerHandler extends ChannelInboundHandlerAdapter{
  23. // @Autowired
  24. // private IWeight weight;
  25. @Autowired
  26. private WeightDataHandle weightDataHandle;
  27. @Override
  28. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  29. //将客户端传入的消息转换为Netty的ByteBuf类型
  30. ByteBuf in = (ByteBuf) msg;
  31. // 在控制台打印传入的消息
  32. // System.out.println(
  33. // "Server received: " + in.toString(CharsetUtil.UTF_8)
  34. // );
  35. String receiveInfo = in.toString(CharsetUtil.UTF_8);
  36. //处理数据
  37. weightDataHandle.handleReceiveData(receiveInfo);
  38. //将接收到的消息写给发送者,而不冲刷出站消息 (应答)
  39. ctx.write(in);
  40. }
  41. @Override
  42. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  43. // 将未处决消息冲刷到远程节点, 并且关闭该Channel
  44. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
  45. .addListener(ChannelFutureListener.CLOSE);
  46. }
  47. /**
  48. * 异常处理
  49. * @param ctx
  50. * @param cause
  51. * @throws Exception
  52. */
  53. @Override
  54. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  55. //打印异常栈跟踪
  56. cause.printStackTrace();
  57. // 关闭该Channel
  58. ctx.close();
  59. }
  60. }