|
@@ -0,0 +1,55 @@
|
|
|
|
+package com.zhentao.information.netty;
|
|
|
|
+
|
|
|
|
+import com.zhentao.information.handler.WebSocketHandler;
|
|
|
|
+import io.netty.bootstrap.ServerBootstrap;
|
|
|
|
+import io.netty.channel.ChannelInitializer;
|
|
|
|
+import io.netty.channel.socket.SocketChannel;
|
|
|
|
+import io.netty.handler.codec.http.HttpObjectAggregator;
|
|
|
|
+import io.netty.handler.codec.http.HttpServerCodec;
|
|
|
|
+import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
|
|
|
|
+import io.netty.handler.stream.ChunkedWriteHandler;
|
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
|
+import org.springframework.beans.factory.annotation.Value;
|
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
|
+
|
|
|
|
+import javax.annotation.PostConstruct;
|
|
|
|
+import javax.annotation.Resource;
|
|
|
|
+
|
|
|
|
+/**
|
|
|
|
+ * Netty服务器启动类
|
|
|
|
+ * 启动动一个基于 Netty 的 WebSocket 服务器
|
|
|
|
+ * 启动 WebSocket 服务器:
|
|
|
|
+ * 它会配置一个 Netty 的 ServerBootstrap,并绑定到指定的端口(默认是 8888)。
|
|
|
|
+ * 它会初始化一个 Netty 的通道管道(ChannelPipeline),并添加各种处理器来处理 WebSocket 连接和消息。
|
|
|
|
+ */
|
|
|
|
+@Slf4j
|
|
|
|
+@Component
|
|
|
|
+public class NettyServer {
|
|
|
|
+
|
|
|
|
+ @Value("${netty.port:8888}")
|
|
|
|
+ private int port;
|
|
|
|
+
|
|
|
|
+ @Resource
|
|
|
|
+ private ServerBootstrap serverBootstrap;
|
|
|
|
+
|
|
|
|
+ @Resource
|
|
|
|
+ private WebSocketHandler webSocketHandler;
|
|
|
|
+
|
|
|
|
+ @PostConstruct
|
|
|
|
+ public void start() throws Exception {
|
|
|
|
+ serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
|
|
|
|
+ @Override
|
|
|
|
+ protected void initChannel(SocketChannel ch) {
|
|
|
|
+ ch.pipeline()
|
|
|
|
+ .addLast(new HttpServerCodec())
|
|
|
|
+ .addLast(new ChunkedWriteHandler())
|
|
|
|
+ .addLast(new HttpObjectAggregator(65536))
|
|
|
|
+ .addLast(new WebSocketServerProtocolHandler("/ws"))
|
|
|
|
+ .addLast(webSocketHandler);
|
|
|
|
+ }
|
|
|
|
+ });
|
|
|
|
+
|
|
|
|
+ serverBootstrap.bind(port).sync();
|
|
|
|
+ log.info("Netty服务器启动成功,端口:{}", port);
|
|
|
|
+ }
|
|
|
|
+}
|