Netty之WebSocket实例

WebSocket

WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补充规范。WebSocket API也被W3C定为标准。

WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

实例

实例要求:

  1. Http协议是无状态的, 浏览器和服务器间的请求响应一次,下一次会重新创建连接.
  2. 要求:实现基于webSocket的长连接的全双工的交互
  3. 改变Http协议多次请求的约束,实现长连接了, 服务器可以主动发送消息给浏览器
  4. 客户端浏览器和服务器端会相互感知,比如服务器关闭了,浏览器会感知,同样浏览器关闭了,服务器会感知。

服务端

image-20201122154306665

                            //因为基于Http协议,使用Http的编码和解码器
                            pipeline.addLast(new HttpServerCodec());
                            //是以块方式写,添加ChunkedWriteHandler处理器
                            pipeline.addLast(new ChunkedWriteHandler());
                            //1.Http数据在传输过程中是分段,HttpObjectAggregator,就是可以将多个段聚合
                            //2.这就是为什么,当浏览完发送大量数据时,就会发出多次Http请求。
                            pipeline.addLast(new HttpObjectAggregator(8192));
                            /***
                             * 1.对应websocket,它对数据是以帧(frame)形式传递
                             * 2.可以看到WebSocketFrame 下面有六个子类
                             * 3.浏览器请求时:ws://localhost:7000/hello 表示请求的uri
                             * 4.WebSocketServerProtocolHandler 核心功能是将Http协议升级为ws协议,从而保持长连接
                             */
                            pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));//ws://localhost:7000/hello
public class MyServer {

    public static void main(String[] args) {
        //创建两个线程组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(8);

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.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());
                            //是以块方式写,添加ChunkedWriteHandler处理器
                            pipeline.addLast(new ChunkedWriteHandler());
                            //1.Http数据在传输过程中是分段,HttpObjectAggregator,就是可以将多个段聚合
                            //2.这就是为什么,当浏览完发送大量数据时,就会发出多次Http请求。
                            pipeline.addLast(new HttpObjectAggregator(8192));
                            /***
                             * 1.对应websocket,它对数据是以帧(frame)形式传递
                             * 2.可以看到WebSocketFrame 下面有六个子类
                             * 3.浏览器请求时:ws://localhost:7000/hello 表示请求的uri
                             * 4.WebSocketServerProtocolHandler 核心功能是将Http协议升级为ws协议,从而保持长连接
                             */
                            pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));

                            //自定义对handler,处理业务逻辑
                            pipeline.addLast(new MyTextWebSocketFrameHandler());
                        }
                    });

            //启动服务器
            ChannelFuture channelFuture = bootstrap.bind(7000).sync();

            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

自定义处理器

image-20201122155303480

TextWebSocketFrame文本桢的形式交互

channel的ID有两种形式

  1. ctx.channel().id().asLongText()唯一

  2. ctx.channel().id().asShortText()不唯一

客户端页面

HTML5 WebSocket:www.runoob.com/html/html5-…

image-20201122160120082

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var socket;
    //判断当前浏览器是否支持websocket
    if(window.WebSocket) {
        //go on
        socket = new WebSocket("ws://localhost:7000/hello");
        //相当于channelRead0, ev 收到服务器端回送的消息
        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" + "连接关闭了.."
        }
    } else {
        alert("当前浏览器不支持websocket")
    }

    //发送消息到服务器
    function send(message) {
        if(!window.socket) { //先判断socket是否创建好
            return;
        }
        if(socket.readyState == WebSocket.OPEN) {
            //通过socket 发送消息
            socket.send(message)
        } else {
            alert("连接没有开启");
        }
    }
</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>

测试

启动服务器

image-20201122160219520

访问页面

image-20201122160252263

发送消息

image-20201122160353263image-20201122160456424

服务器可以发送消息给浏览器

关闭页面,断开连接(这里服务器我重启了ID所以不一样)。

image-20201122160728047

关闭服务器

image-20201122160853624

客户端浏览器和服务器端会相互感知,比如服务器关闭了,浏览器会感知,同样浏览器关闭了,服务器会感知。

细节

WebSocket服务器通过101状态码切换协议由http->ws。

image-20201122161625265

© 版权声明
THE END
喜欢就支持一下吧
点赞0

Warning: mysqli_query(): (HY000/3): Error writing file '/tmp/MYO2YHa2' (Errcode: 28 - No space left on device) in /www/wwwroot/583.cn/wp-includes/class-wpdb.php on line 2345
admin的头像-五八三
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

图形验证码
取消
昵称代码图片