netty websocket 小 demo

websokct 使用 netty 实现

websocket 是一个全双工的长连接通讯

话不多说直接上代码。。

服务端的代码实现

public void init() throws InterruptedException {
        EventLoopGroup boosGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boosGroup, workGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            // http 编码和解编码 handler
                            pipeline.addLast(new HttpServerCodec());
                            // chunked 以块的形式 handler
                            pipeline.addLast(new ChunkedWriteHandler());
                            // http 数据传输过程中是分段的, httpObjectAggregator 就可以给多个段做聚合操作,这就是浏览器发送大量数据时候,就会发出多次 http 请求
                            pipeline.addLast(new HttpObjectAggregator(8192));
                            // webSocket 是通过帧的形式传递的,可以看到 WebSocketFrame 六个子类,WebSocketServerProtocolHandler 他的主要功能就是可以把 http 协议升级为 ws 协议,保持长连接
                            pipeline.addLast(new WebSocketServerProtocolHandler("/msg"));
                            pipeline.addLast(new CustomWebSocketFrameTextHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(88).sync();
            channelFuture.addListener(future -> {
                if (future.isDone()) log.info("端口绑定成功");
            });
            channelFuture.channel().closeFuture().sync();
        } finally {
            boosGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

服务端的逻辑会用到自定义handler的处理器 CustomWebSocketFrameTextHandler 这个自定义处理器。

处理器的代码

/**
     * 这里的 {@link TextWebSocketFrame} 表示一个文本帧
     *
     * @author L
     */
    class CustomWebSocketFrameTextHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

        Logger log = LoggerUtils.getLogger(CustomWebSocketFrameTextHandler.class);

        /**
         * 当 web 客户端连接以后就会触发这个方法
         */
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) {
            // id 表示唯一的值信息,LongText 是唯一的。ShortText 不是唯一的
            log.info("handlerAdded => {} 被调用", ctx.channel().id().asLongText());
            log.info("handlerAdded => {} 被调用", ctx.channel().id().asShortText());
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
            String text = msg.text();
            log.info("{}", text);
            // 回复客户端消息
            ctx.writeAndFlush(new TextWebSocketFrame(text));
        }

        /**
         * 断开连接以后会触发
         */
        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) {
            log.info("handlerRemoved => {} 被调用", ctx.channel().id().asLongText());
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            log.error("发生异常 => {}", cause.getMessage());
        }
    }

服务端这就可以运行了。然后需要一个客户端来测试。客户端需要直接编写一个 html 的简单的小页面来测试。

let webSocket = null;

    if (window.WebSocket) {
        // 逻辑
        webSocket = new WebSocket("ws://localhost:88/msg");
        webSocket.onopen = () => {
            let showPlace = document.getElementById("responseMessage");
            showPlace.value = "连接开启";
        }
        webSocket.onmessage = function (p) {
            let showPlace = document.getElementById("responseMessage");
            showPlace.value = showPlace.value + "\r\n" + p.data;
        }
        webSocket.onclose = () => {
            let showPlace = document.getElementById("responseMessage");
            showPlace.value = showPlace.value + "\r\n" + "连接关闭";
        }
        webSocket.onerror = (p) => {
            let showPlace = document.getElementById("responseMessage");
            showPlace.value = showPlace.value + "\r\n" + "连接错误 => " + p.type;
        }
    } else alert("当前浏览器不支持操作");

    function send(msg) {
        if (webSocket.OPEN) {
            webSocket.send(msg);
        }
    }

这样就实现了 netty的 websocket 服务

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值