美文网首页
Netty-WebSocket长连接开发

Netty-WebSocket长连接开发

作者: 养一只tom猫 | 来源:发表于2021-03-04 10:27 被阅读0次
    public class WebSocketServer {
        public static void main(String[] args) throws Exception {
            EventLoopGroup boosGroup = new NioEventLoopGroup();
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                ServerBootstrap serverBootstrap = new ServerBootstrap();
                serverBootstrap.group(boosGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();
                                // http编解码handler
                                pipeline.addLast(new HttpServerCodec());
                                // http是以块的方式写
                                pipeline.addLast(new ChunkedWriteHandler());
                                // http在大量数据时,请求会分多次发送,HttpObjectAggregator将多个请求聚合在一起
                                pipeline.addLast(new HttpObjectAggregator(2048));
                                // 设置路径,WebSocketServerProtocolHandler 核心功能是将http协议升级为ws协议
                                pipeline.addLast(new WebSocketServerProtocolHandler("/demo"));
                                // 自定义handler处理事件
                                pipeline.addLast(new WebSocketServerHandler());
                            }
                        });
    
                ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
                channelFuture.channel().closeFuture().sync();
            } finally {
                boosGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }
    }
    
    public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
            System.out.println("接受到消息: " + msg.text());
            ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器回复: " + msg.text()));
        }
    
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            System.out.println("新建连接");
        }
    
        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
            System.out.println("断开连接");
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println(cause.getMessage());
            ctx.close();
        }
    }
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
    <form>
        <input type="text" id="inputMessage" style="height: 500px; width: 500px">
        <input type="button" value="发送消息" onclick="send(this.form.inputMessage.value)">
    </form>
    </body>
    <script>
        var socket;
    
        if (window.WebSocket) {
    
            socket = new WebSocket("ws://localhost:8888/demo");
    
            socket.onmessage = function (ev) {
                alert(ev.data);
            };
    
            socket.onopen = function (ev) {
                alert("连接开启");
            };
    
            socket.onclose = function (ev) {
                alert("连接关闭");
            };
    
        } else {
            alert("当前浏览器不支持websocket");
        }
    
        function send(message) {
            if (!window.socket) {
                return;
            }
            if (socket.readyState === WebSocket.OPEN) {
                socket.send(message);
            }
        }
    </script>
    
    </html>
    

    相关文章

      网友评论

          本文标题:Netty-WebSocket长连接开发

          本文链接:https://www.haomeiwen.com/subject/tsghqltx.html