Netty通过WebSocket编程实现服务器和客户端长连接

本文介绍如何利用Netty框架构建WebSocket服务器,并配合前端页面建立长连接。服务器端通过自定义Handler处理WebSocket连接,前端页面则实现与服务器的WebSocket通信,确保双向实时通信的稳定。
摘要由CSDN通过智能技术生成

在这里插入图片描述

服务器端

public class MyServer {
    public static void main(String[] args) throws Exception {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO)) //在bossGroup增加一个日志处理器
                    .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());
                            /**
                             * 因为http协议传输过程中是分段的、HttpObjectAggregator可以将多个段进行聚合
                             * 所以浏览器发送大量数据时、会发出多次http请求
                             */
                            pipeline.addLast(new HttpObjectAggregator(8192));
                            /**
                             * 对应WebSocket ,他的数据以帧方式传递
                             * WebSocketServer下面有六个子类
                             * 浏览器请求时 ws://localhost:9999/hello 表示请求的uri
                             * WebSocketServerProtocolHandler 核心功能是将http协议升级为ws协议,保持长连接
                             */
                            pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));

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

            ChannelFuture channelFuture = serverBootstrap.bind(9999).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

自定义Handler

public class MyTextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("服务器端收到消息 " + msg.text());

        //回复浏览器消息
        ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间 " + LocalDateTime.now() + " " + msg.text()));

    }
    //当web客户端连接后、触发方法
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //id表示唯一的标识,LongText是唯一的  ShortText不是唯一的
        System.out.println("handlerAdded被调用了"+ctx.channel().id().asLongText());
        System.out.println("handlerAdded被调用了"+ctx.channel().id().asShortText());
        super.handlerAdded(ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerRemoved被调用了"+ctx.channel().id().asLongText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常发生" + cause.getMessage());
        ctx.close(); //关闭连接

    }
}

前端页面代码

<!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:9999/hello");
        //相当于channelRead 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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值