|
|
@@ -0,0 +1,37 @@
|
|
|
+package com.zksy.server;
|
|
|
+
|
|
|
+import com.zksy.service.ChatService;
|
|
|
+import io.netty.bootstrap.ServerBootstrap;
|
|
|
+import io.netty.channel.ChannelFuture;
|
|
|
+import io.netty.channel.EventLoopGroup;
|
|
|
+import io.netty.channel.nio.NioEventLoopGroup;
|
|
|
+import io.netty.channel.socket.nio.NioServerSocketChannel;
|
|
|
+
|
|
|
+public class WebSocketServer {
|
|
|
+ private final int port;
|
|
|
+ private final ChatService chatService;
|
|
|
+
|
|
|
+ public WebSocketServer(int port, ChatService chatService) {
|
|
|
+ this.port = port;
|
|
|
+ this.chatService = chatService;
|
|
|
+ }
|
|
|
+
|
|
|
+ public void start() throws InterruptedException {
|
|
|
+ EventLoopGroup boss = new NioEventLoopGroup(1);
|
|
|
+ EventLoopGroup worker = new NioEventLoopGroup();
|
|
|
+
|
|
|
+ try {
|
|
|
+ ServerBootstrap bootstrap = new ServerBootstrap();
|
|
|
+ bootstrap.group(boss, worker)
|
|
|
+ .channel(NioServerSocketChannel.class)
|
|
|
+ .childHandler(new WebSocketServerInitializer(chatService));
|
|
|
+
|
|
|
+ ChannelFuture future = bootstrap.bind(port).sync();
|
|
|
+ System.out.println("WebSocket 服务器已启动,端口:" + port);
|
|
|
+ future.channel().closeFuture().sync();
|
|
|
+ } finally {
|
|
|
+ boss.shutdownGracefully();
|
|
|
+ worker.shutdownGracefully();
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|