NettyClient.java 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package com.yx.face.netty_client;
  2. import io.netty.bootstrap.Bootstrap;
  3. import io.netty.channel.ChannelFuture;
  4. import io.netty.channel.ChannelOption;
  5. import io.netty.channel.EventLoopGroup;
  6. import io.netty.channel.nio.NioEventLoopGroup;
  7. import io.netty.channel.socket.SocketChannel;
  8. import io.netty.channel.socket.nio.NioSocketChannel;
  9. import lombok.SneakyThrows;
  10. import lombok.extern.slf4j.Slf4j;
  11. import org.springframework.scheduling.annotation.Async;
  12. import org.springframework.stereotype.Component;
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. /**
  16. * @ProjectName: face-server
  17. * @Package: com.yx.face.nettyserver
  18. * @ClassName: NettyClient
  19. * @Author: 崔哥
  20. * @Description: 接收自有项目消息
  21. * @Date: 2021/11/22 13:18
  22. * @Version: 1.0
  23. */
  24. @Component
  25. @Slf4j
  26. public class NettyClient {
  27. private static int port = 9899;
  28. private static String host = "127.0.0.1";
  29. public static Bootstrap bootstrap = null;
  30. public static SocketChannel socketChannel = null;
  31. public static ChannelFuture future = null;
  32. public Map<String, Bootstrap> map = new HashMap<>();
  33. /**
  34. * 向监管平台发送消息
  35. *
  36. * @param msg 接收到的自有项目传递过来的消息
  37. * @return
  38. * @throws InterruptedException
  39. */
  40. @Async
  41. @SneakyThrows
  42. public void sendMessage(String msg) {
  43. if (!map.containsKey(host)) {
  44. log.info("-------------------------新建连接服务端:" + host + ":" + port + "---------------------------");
  45. EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
  46. bootstrap = new Bootstrap();
  47. bootstrap.channel(NioSocketChannel.class);
  48. bootstrap.group(eventLoopGroup);
  49. bootstrap.remoteAddress(host, port);
  50. // 设置超时时间
  51. bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);
  52. map.put(host, bootstrap);
  53. } else {
  54. log.info("--------------------------已连接服务端:" + host + ":" + port + "-----------------------------");
  55. bootstrap = map.get(host);
  56. }
  57. NettyChannelInitializer customerChannelInitializer = new NettyChannelInitializer(msg);
  58. bootstrap.handler(customerChannelInitializer);
  59. future = bootstrap.connect(host, port).sync();
  60. if (future.isSuccess()) {
  61. socketChannel = (SocketChannel) future.channel();
  62. log.info("远程服务器已经连接, 可以进行数据交换..");
  63. }
  64. }
  65. }