GatewayServer.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package com.zhili.stationcontrol.gatewayserver.component;
  2. import com.zhili.stationcontrol.gatewayserver.handler.GatewayMessageDecoder;
  3. import com.zhili.stationcontrol.gatewayserver.handler.GatewayMessageEncoder;
  4. import com.zhili.stationcontrol.gatewayserver.handler.GatewayMessageHandler;
  5. import io.netty.bootstrap.ServerBootstrap;
  6. import io.netty.channel.ChannelFuture;
  7. import io.netty.channel.ChannelInitializer;
  8. import io.netty.channel.ChannelOption;
  9. import io.netty.channel.EventLoopGroup;
  10. import io.netty.channel.nio.NioEventLoopGroup;
  11. import io.netty.channel.socket.SocketChannel;
  12. import io.netty.channel.socket.nio.NioServerSocketChannel;
  13. import lombok.extern.slf4j.Slf4j;
  14. import org.springframework.scheduling.annotation.Async;
  15. import org.springframework.scheduling.annotation.EnableAsync;
  16. import org.springframework.stereotype.Component;
  17. /**
  18. * @author :HuangBin
  19. * @description:TODO
  20. * @date :2022/10/28 15:22
  21. */
  22. @EnableAsync
  23. @Component
  24. @Slf4j
  25. //192.168.3.177:9989
  26. public class GatewayServer {
  27. @Async
  28. public void run() {
  29. EventLoopGroup bossGroup = new NioEventLoopGroup(1);
  30. EventLoopGroup workerGroup = new NioEventLoopGroup();
  31. try {
  32. ServerBootstrap server = new ServerBootstrap();
  33. server.group(bossGroup, workerGroup)
  34. .channel(NioServerSocketChannel.class)
  35. .childOption(ChannelOption.SO_KEEPALIVE, true)
  36. .childOption(ChannelOption.TCP_NODELAY, true)
  37. .option(ChannelOption.SO_BACKLOG, 1024)
  38. .childHandler(new ChannelInitializer<SocketChannel>() {
  39. @Override
  40. protected void initChannel(SocketChannel socketChannel) throws Exception {
  41. socketChannel.pipeline()
  42. .addLast(new GatewayMessageDecoder())
  43. .addLast(new GatewayMessageEncoder())
  44. .addLast(new GatewayMessageHandler());
  45. }
  46. });
  47. ChannelFuture channelFuture = server.bind(9989).sync();
  48. channelFuture.channel().closeFuture().sync();
  49. } catch (InterruptedException e) {
  50. e.printStackTrace();
  51. } finally {
  52. bossGroup.shutdownGracefully();
  53. workerGroup.shutdownGracefully();
  54. }
  55. }
  56. }