netty-websocket

netty-websocket

起男 46 2024-03-28

netty-websocket

服务器

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                    .group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //因为基于http协议,所以要使用http的编解码器
                            pipeline.addLast(new HttpServerCodec());
                            //以块方式写,添加ChunkedWrite处理器
                            pipeline.addLast(new ChunkedWriteHandler());
                            //http的数据在传输的过程中是分段的,HttpObjectAggregator可以将多个段聚合起来
                            //这就是为什么,浏览器发送大量数据时,会发出多次http请求
                            pipeline.addLast(new HttpObjectAggregator(8192));
                            //WebSocketServerProtocolHandler 核心功能是将http协议升级为ws协议(通过101状态码),保存长连接
                            //并且可以识别请求的资源 如ws://localhost:7000/hello
                            pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
                            //自定义handler,处理业务逻辑
                            pipeline.addLast(new MyTestWebSocketFrameHandler());
                        }
                    });
            ChannelFuture cf = serverBootstrap.bind(7000).sync();
            cf.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

自定义处理器

//TextWebSocketFrame:表示一个文本帧(frame)
public class MyTestWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("服务器收到消息:"+msg.text());
        //回复消息
        ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间"+ LocalDateTime.now()
                +" "+msg.text()));
    }

    //当web客户端连接后会触发
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //id:表示唯一的一个值,LongText是唯一的,ShortText可能重复
        System.out.println("handlerAdded 被调用了"+ctx.channel().id().asLongText());
        System.out.println("handlerAdded 被调用了"+ctx.channel().id().asShortText());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerRemoved 被调用"+ctx.channel().id().asLongText());
    }

    @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>

    <script>
        var socket;
        //判断当前浏览器是否支持websocket
        if (window.WebSocket){
            socket = new WebSocket("ws://localhost:7000/hello")
            //相当于channelRead0,收到服务器端回送的消息
            socket.onmessage = function (ev) {
                var rt = document.getElementById('responseText')
                rt.value = rt.value + "\n" + ev.data
            }
            //相当于连接开启(感知到连接开启)
            socket.onopen = function (ev) {
                var rt = document.getElementById('responseText')
                rt.value = "连接开启了。。。"
            }
            //相当于连接关闭(感知到连接关闭)
            socket.onclose = function (ev) {
                var rt = document.getElementById('responseText')
                rt.value = rt.value + "\n" + "连接关闭了。。。"
            }
            //发送消息到服务器
            function send(message) {
                if (!window.socket){//websocket是否创建好
                    return
                }
                if (socket.readyState == WebSocket.OPEN){
                    //通过socket发送消息
                    socket.send(message)
                } else {
                    alert("连接未开启")
                }
            }
        } else {
            alert("当前浏览器不支持websocket")
        }
    </script>

    <form onsubmit="return false">
        <textarea name="message" style="height: 300px; width: 300px"></textarea>
        <input type="button" value="发送消息" onclick="send(this.form.message.value)">
        <textarea id="responseText" style="height: 300px; width: 300px"></textarea>
        <input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
    </form>
</body>
</html>