netty通过websocket实现服务器与客户端的长连接

server端代码
import com.chinadaas.bio.chinadaasbio.webSocket.handler.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class Server {

    public static void main(String[] args) throws Exception {
        NioEventLoopGroup boosGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boosGroup, workerGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 128);
            serverBootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline pipeline = socketChannel.pipeline();
                    // 因为是基于http的 所以使用http的编码和解析器
                    pipeline.addLast(new HttpServerCodec());
                    // 是以块方式写,添加ChunkWriteHandler() 处理器
                    pipeline.addLast(new ChunkedWriteHandler());
                    // http在传输过程中是分段的,这就是为什么当浏览器发送大量数据的时候,会发出多次http请求
                    pipeline.addLast(new HttpObjectAggregator(8192));
                    // 1:对应websocket 他的数据是以帧的形式传递
                    // 2: WebSocketServerProtocolHandler 功能是将http协议升级为ws协议,保持一个长连接
                    pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
                    // 添加自定义的handler
                    pipeline.addLast(new ServerHandler());
                }
            });
            ChannelFuture channelFuture = serverBootstrap.bind(8886).sync();
            channelFuture.channel().closeFuture().sync();

        } finally {
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}
ServerHandler 代码
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDateTime;

public class ServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

        System.out.println("服务器收到消息:" + textWebSocketFrame.text());
        channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame("服务器时间" + LocalDateTime.now() + " " + textWebSocketFrame.text()));

    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress()+"断开了连接");


    }
}
websocket html 代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var socket;
    if (window.WebSocket) {
        socket = new WebSocket("ws://localhost:8886/hello")
        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) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            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>

欢迎大家前来讨论

阅读 262

推荐阅读