第四个Netty程序:长链接的使用

第四个Netty程序:长链接的使用

目的及介绍

  • 通过WebSocket模仿TCP长链接

项目源码

  • HighAvailability_HighConcurrency_HighPerformance

搭建、设计思路

  • 在service的childHandler的pipeline中加入HttpObjectAggregator和WebSocketServerProtocolHandler
  • HttpObjectAggregator主要用于对信息按照指定大小分块
  • WebSocketServerProtocolHandler主要用于指定访问路径
  • 收到的消息在TextWebSocketFrameHandle04中输出

具体步骤

  • 服务端Server04的代码
public class Server04 {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossExecutors = new NioEventLoopGroup();
        EventLoopGroup workExecutors = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossExecutors,workExecutors).channel(NioServerSocketChannel.class).
                    //handler是用于处理bossExecutors
                    //childHandler是用于处理workExecutors
                    handler(new LoggingHandler(LogLevel.INFO)).
                    childHandler(new WebSocketInitializer04());

            ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(9050)).sync();
            channelFuture.channel().closeFuture().sync();

        }finally {
            bossExecutors.shutdownGracefully();
            workExecutors.shutdownGracefully();
        }
    }
}
  • 服务端WebSocketInitializer04的代码
public class WebSocketInitializer04 extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpObjectAggregator(8192));
        pipeline.addLast(new WebSocketServerProtocolHandler("/ljfirst"));
        pipeline.addLast(new TextWebSocketFrameHandle04());
    }
}
  • 客户端模拟交互的网页

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>long connectiontitle>
head>
<body>
<script type="text/javascript">
    var socket;
    if (window.WebSocket) {
        socket = new WebSocket("ws://localhost:9050/ljfirst");

        socket.onmessage = function (event) {
            var ta = document.getElementById("responsetext");
            ta.value = ta.value + "\n" + event.data;
        }

        socket.onopen = function (event) {
            var tt = document.getElementById("responsetext");
            tt.value = "连接开启";
        }

        socket.onclose = function (event) {
            var clt = document.getElementById("responsetext");
            clt.value = clt.value + "\n" + "连接断掉";
        }
    } else {
        alert("浏览器不支持websocket")
    }

    function send(msg) {
        if (!window.WebSocket) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(msg);
        }else {
            alert("连接尚未开启");
        }
    }

script>


<form onsubmit="return false;">

    
    <textarea name="msg" style="width: 400px; height: 200px">textarea>
    <input type="button"  onclick="send(this.form.msg.value)" value="发送">

    <h3>服务端输出:h3>
    <textarea id="responsetext" style="width: 400px; height: 200px">textarea>
    <input type="button" onclick="javascript: document.getElementById('responsetext').value=''" value="清空内容">


form>
body>
html>

排坑细节

  • pipeline.addLast(new HttpObjectAggregator(8192));这一句中的8192是分块大小
  • html网页中form的textarea中的name 与 script中function的name需要对应

你可能感兴趣的:(高并发,高可用,高性能专题)