基于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:


"en">

    "UTF-8">
    Title



"return false"> "button" value="send message" οnclick="send(this.form.message.value)"> "button" value="clear" οnclick="document.getElementById('response').value=''">

实验效果:

基于Netty的简单webSocket响应聊天代码_第1张图片

你可能感兴趣的:(Netty)