基于Netty的简单webSocket响应聊天代码

服务器:

package WebSocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 MyServer {
    public static void main(String[] args) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new HttpServerCodec())//基于http协议
                                    .addLast(new ChunkedWriteHandler())//以块的方式写
                                    .addLast(new HttpObjectAggregator(8192))//将http数据传输过程中的分段聚合
                                    .addLast(new WebSocketServerProtocolHandler("/test"))//将http协议升级为webSocket协议,保持长连接
                                    .addLast(new MyserverHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

服务器Handler:

package WebSocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDateTime;

//webSocket数据是以帧的方式传输的,TextWebSocketFrame类型表示一个文本帧
public class MyserverHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {

        System.out.println("服务器收到消息:\t" + msg.text());
        //回复消息
        ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间:" + LocalDateTime.now() + "\n" + msg.text()));

    }

    //该方法触发于web客户端连接后
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //ctx.channel().id().asLongText()输出的id唯一
        System.out.println("web客户端连接:\t" + ctx.channel().id().asLongText());
        //ctx.channel().id().asShortText()输出的id不唯一
        System.out.println("web客户端连接:\t" + ctx.channel().id().asShortText());
    }

    //该方法触发于web客户端连接断开
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("web客户端断开:\t" + ctx.channel().id().asLongText());
    }

    //异常处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

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:7000/test");
        socket.onmessage = function (ev) {
            var rmsg = document.getElementById('response');
            rmsg.value = rmsg.value + "\n" + ev.data;
        }
        socket.onopen = function () {
            var rmsg = document.getElementById('response');
            rmsg.value = "连接开启";
        }
        socket.onclose = function () {
            var rmsg = document.getElementById('response');
            rmsg.value = rmsg.value + "\n" + "连接关闭";
        }
    } else {
        alert("该浏览器不支持webSocket");
    }

    function send(message) {
        if (!window.socket) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(message);
        } else {
            alert("连接没有开启");
        }
    }
</script>
<form οnsubmit="return false">
    <textarea name="message" style="height: 400px;width: 400px"></textarea>
    <input type="button" value="send message" οnclick="send(this.form.message.value)">
    <textarea id="response" style="height: 400px;width: 400px"></textarea>
    <input type="button" value="clear" οnclick="document.getElementById('response').value=''">
</form>
</body>
</html>

实验效果:

在这里插入图片描述

发布了61 篇原创文章 · 获赞 0 · 访问量 286

猜你喜欢

转载自blog.csdn.net/weixin_43490369/article/details/104734312
今日推荐