公告:魔扣目录网为广大站长提供免费收录网站服务,提交前请做好本站友链:【 网站目录:https://www.morko.net 】, 免友链快审服务(50元/站),

点击这里在线咨询客服
新站提交
  • 网站:51998
  • 待审:31
  • 小程序:12
  • 文章:1030137
  • 会员:747

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 + "rn" + p.data;
        }
        webSocket.onclose = () => {
            let showPlace = document.getElementById("responseMessage");
            showPlace.value = showPlace.value + "rn" + "连接关闭";
        }
        webSocket.onerror = (p) => {
            let showPlace = document.getElementById("responseMessage");
            showPlace.value = showPlace.value + "rn" + "连接错误 => " + p.type;
        }
    } else alert("当前浏览器不支持操作");

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

这样就实现了 netty的 websocket 服务

分享到:
标签:webSocket
用户无头像

网友整理

注册时间:

网站:5 个   小程序:0 个  文章:12 篇

  • 51998

    网站

  • 12

    小程序

  • 1030137

    文章

  • 747

    会员

赶快注册账号,推广您的网站吧!
最新入驻小程序

数独大挑战2018-06-03

数独一种数学游戏,玩家需要根据9

答题星2018-06-03

您可以通过答题星轻松地创建试卷

全阶人生考试2018-06-03

各种考试题,题库,初中,高中,大学四六

运动步数有氧达人2018-06-03

记录运动步数,积累氧气值。还可偷

每日养生app2018-06-03

每日养生,天天健康

体育训练成绩评定2018-06-03

通用课目体育训练成绩评定