netty 起 WebSocket server

class WebSocketServer {
    private final static Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
    private final int port = 5516;

    private final EventLoopGroup bossGroup = new NioEventLoopGroup();
    private final EventLoopGroup workerGroup = new NioEventLoopGroup();

    public void start() {
        ServerBootstrap bootstrap = new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 512)
                .childHandler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpServerCodec());
                        ch.pipeline().addLast(new ChunkedWriteHandler());
                        ch.pipeline().addLast(new HttpObjectAggregator(65536));
                        ch.pipeline().addLast(new WebSocketServerProtocolHandler("/pumpEvent"));
                        ch.pipeline().addLast(new WebSocketHandler());
                    }
                });
        try {
            ChannelFuture bindFuture = bootstrap.bind(port).sync();
            bindFuture.channel().closeFuture().addListener(future -> {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            });
            logger.info("{} is started on port {}.", this.getClass().getSimpleName(), port);
        } catch (Exception e) {
            logger.error("{} starts failed!", this.getClass().getSimpleName(), e);
        }
    }

    public void stop() {
        logger.info("{} stopped.", this.getClass().getSimpleName());
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

    class WebSocketHandler extends SimpleChannelInboundHandler {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        }
    }
}

你可能感兴趣的:(netty 起 WebSocket server)