netty对于websocket的支持

websocket协议

要实现网页版的聊天室,用http协议是不行的,因为http协议是个短链接,发过去之后拿到响应就死掉了。

http1.1出现了keepAlive。这里可以实现长连接。

所谓长连接,就是可以重用之前建立的tcp连接。

但是,keepAlive是一个假的长连接。server可以随时断掉,server和client是不对等的状态。另外,它的实现是client要不断向server询问是否有新数据,每次询问的时候,都要携带header(http协议规范),这些不必要的数据,增加了网络带宽的压力。

于是,出现了能够真正实现长连接的websocket协议。

在该协议下,tcp连接建立之后,client和server的交互不再需要携带header。并且,client和server是对等的,它们都可以向对方发送信息。

netty server

server:

public class WebSocketServer {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new WebSocketServerInitializer());

            ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
            channelFuture.channel().closeFuture().sync();

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

Initializer:

public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        pipeline.addLast("httpServerCodec",new HttpServerCodec());
        pipeline.addLast("streamer",new ChunkedWriteHandler());
        pipeline.addLast(new HttpObjectAggregator(8192));
        pipeline.addLast(new WebSocketServerProtocolHandler("/websocketpath"));

        pipeline.addLast(new TextWebSocketFrameHandler());
    }
}

这里有几个handler:

HttpServerCodecHttpRequestDecoderHttpResponseEncoder的组合。

ChunkedWriteHandler支持异步地写出大数据量文件。

HttpObjectAggregatorHttpMessageHttpContent整合成一个FullHttpRequest或者FullHttpResponse。如果我们的传输编码方式是chunked(一块一块的),我们就不用去担心http消息了,因为HttpObjectAggregator会帮我们整合好。

WebSocketServerProtocolHandler是封装websocket协议的handler。

/**
 * This handler does all the heavy lifting for you to run a websocket server.
 *
 * It takes care of websocket handshaking as well as processing of control frames (Close, Ping, Pong). Text and Binary
 * data frames are passed to the next handler in the pipeline (implemented by you) for processing.
 */

文档说,WebSocketServerProtocolHandler会处理Text data frame,我们接下来要用的也是这个frame。

TextWebSocketFrameHandler:

public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("receive message: " + msg.text());

        ctx.writeAndFlush(new TextWebSocketFrame("server time: " + LocalTime.now()));
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("TextWebSocketFrameHandler added. " + ctx.channel().id().asLongText());
    }

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

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        System.out.println("exception caught!");
        ctx.close();
    }
}




我们会打印客户端发来的数据并且将服务器的时间返回出去。

client

客户端我们用html和js来写:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>websocket chat</title>
</head>

<script type="text/javascript">
    let socket;
    if(window.WebSocket){
        socket = new WebSocket("ws://localhost:8888/websocketpath");

        socket.onmessage = function (event) {
            const content = document.getElementById("responseText");
            content.value = content.value + "\n" + event.data;
        }

        socket.onopen = function (event) {
            const content = document.getElementById("responseText");
            content.value = "connection open!";
        }
        socket.onclose = function (event) {
            const content = document.getElementById("responseText");
            content.value = content.value + "\n" + "connection closed!";
        }
    }else {
        alert("browser doesn't support websocket!")
    }

    function send(message) {
        if(!window.WebSocket){
            return;
        }
        if(socket.readyState == WebSocket.OPEN){
            socket.send(message);
        }else{
            alert("no connection!");
        }
    }

</script>
<body>

<form onsubmit="return false;">

    <h3>client send message</h3>
    <textarea name="message" style="width: 400px; height: 200px"></textarea>
    <input type="button" value="send" onclick="send(this.form.message.value)">

    <h3>server output: </h3>
    <textarea id="responseText" style="width: 400px; height: 200px"></textarea>
    <input type="button" onclick="javascript: document.getElementById('responseText').value=''" value="clear">
</form>

</body>
</html>


基于websocket协议的地址是这么写的:

ws://localhost:8888/websocketpath

ws指的是协议,后面的websocketpath与服务端配置的websocketHandler的接收地址是一样的:

  pipeline.addLast(new WebSocketServerProtocolHandler("/websocketpath"));

我们在js脚本中对于连接建立、断开、有消息传输都配置了对应的回调函数。

大概的样子是这样的:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值