Netty 实现服务端

100 阅读1分钟

使用Netty创建一个服务端,完整代码如下:

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
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.HttpServerCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator;
import io.netty.channel.SimpleChannelInboundHandler;

public class NettyServer {
    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                     .channel(NioServerSocketChannel.class)
                     .childHandler(new ChannelInitializer<SocketChannel>() {
                         @Override
                         public void initChannel(SocketChannel ch) throws Exception {
                             ChannelPipeline pipeline = ch.pipeline();
                             // 用于处理HTTP请求和响应的编解码
                             pipeline.addLast(new HttpServerCodec());
                             // 用于处理大数据流写入
                             pipeline.addLast(new ChunkedWriteHandler());
                             // 用于聚合HTTP消息的内容
                             pipeline.addLast(new HttpObjectAggregator(64 * 1024));
                             // 用于处理WebSocket协议的握手和帧
                             pipeline.addLast(new WebSocketServerProtocolHandler("/websocket"));
                             pipeline.addLast(new WebSocketFrameAggregator(64 * 1024));
                                   // 自定义处理器,用于处理自定义通讯的逻辑,包括文本消息的处理
                             pipeline.addLast(new WsTextMessageHandler());
                                   // 自定义处理器,用于处理自定义通讯的逻辑,包括二进制消息的处理
                             pipeline.addLast(new WsBinaryMessageHandler());
                         }
                     });
            
            ChannelFuture future = bootstrap.bind(8080).sync();
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
    //  pipeline.addLast(new WsTextMessageHandler())的WsTextMessageHandler实现
    // 用于处理自定义通讯的逻辑,包括文本消息的处理
    public static class WsTextMessageHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
            // 处理接收到的文本消息逻辑
            System.out.println("Received text message: " + msg.text());
            // 回复消息
            ctx.writeAndFlush(new TextWebSocketFrame("Hello, WebSocket!"));
        }
    }
    
    //  pipeline.addLast(new WsBinaryMessageHandler())的WsBinaryMessageHandler实现
    public static class WsBinaryMessageHandler extends SimpleChannelInboundHandler<BinaryWebSocketFrame> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, BinaryWebSocketFrame msg) throws Exception {
            // 处理接收到的二进制消息逻辑
            byte[] data = new byte[msg.content().readableBytes()];
            msg.content().readBytes(data);
            System.out.println("Received binary message: " + new String(data));
            // 回复消息
            ctx.writeAndFlush(new BinaryWebSocketFrame(msg.content()));
        }
    }
}