Netty笔记(一)之客户端与服务端代码分析

本文详细分析了Netty的客户端和服务端代码。首先介绍了Netty的版本,接着讲解了服务端的启动代码,包括事件循环组的创建和服务器端口的绑定。然后阐述了服务端Handler的职责,特别是其入站数据处理和异常处理。客户端部分,讨论了Bootstrap的配置,如通道类型、通道选项和属性设置,以及客户端Handler如何处理接收到的数据。最后强调了ByteBuf的使用以及消息的释放策略。
摘要由CSDN通过智能技术生成

netty版本

  1. netty版本:io.netty:netty-all:4.1.33.Final

server端代码

启动代码

  1. 启动主流程代码分析

        public class EchoServer {
         
        
            private final int port;
            public EchoServer(int port) {
         
                this.port = port;
            }
            public void start() throws Exception {
         
                //使用NIO事件循环组来接受和处理新的连接, OIO可以使用OioEventLoopGroup()
                NioEventLoopGroup group = new NioEventLoopGroup();
                try {
         
                    //ServerBootstrap 是一个启动NIO服务的辅助启动类 你可以在这个服务中直接使用Channel
                    ServerBootstrap b = new ServerBootstrap();                            //#1
                    //这一步是必须的,如果没有设置group将会报java.lang.IllegalStateException: group not set异常
                    b.group(group)                                                        //#2
                            //指定NIO传输类型
                            .channel(NioServerSocketChannel.class)                        //#2
                            //本地套接字地址
                            .localAddress(new InetSocketAddress(port))                    //#2
                            //把处理器加入到channel pipeline                       
                            .childHandler(new ChannelInitializer<SocketChannel>() {
                //#3
                                //每个连接上一个连接调用一次
                                @Override
                                public void initChannel(SocketChannel ch)
                                        throws Exception {
         
                                    //设置childHandler执行所有的连接请求
                                    ch.pipeline().addLast(new EchoServerHandler());      //#4
                                }
                            });
                    //异步绑定服务器,sync()方法的调用将引起这个阻塞,直到服务器绑定完成.
                    ChannelFuture f = b.bind().sync();                                    //#5
                    System.out.println(EchoServer.class.getName() +     
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是一个使用 Netty 实现 WebSocket 服务端客户端的示例代码服务端代码: ```java public class WebSocketServer { public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap() .group(group) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new WebSocketServerProtocolHandler("/chat")); pipeline.addLast(new TextWebSocketFrameHandler()); } }); ChannelFuture future = bootstrap.bind(8080).sync(); future.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } private static class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { private final List<Channel> channels = new ArrayList<>(); @Override protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { String text = msg.text(); System.out.println("Received message: " + text); for (Channel channel : channels) { channel.writeAndFlush(new TextWebSocketFrame("Server: " + text)); } } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { channels.add(ctx.channel()); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { channels.remove(ctx.channel()); } } } ``` 客户端代码: ```java public class WebSocketClient { public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker( new URI("ws://localhost:8080/chat"), WebSocketVersion.V13, null, false, new DefaultHttpHeaders())); Bootstrap bootstrap = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpClientCodec()); pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new WebSocketClientProtocolHandler(handler.handshaker())); pipeline.addLast(handler); } }); Channel channel = bootstrap.connect("localhost", 8080).sync().channel(); handler.handshakeFuture().sync(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true) { String line = reader.readLine(); if (line == null) { break; } channel.writeAndFlush(new TextWebSocketFrame(line)); } } finally { group.shutdownGracefully(); } } private static class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> { private final WebSocketClientHandshaker handshaker; private ChannelPromise handshakeFuture; public WebSocketClientHandler(WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; } public ChannelFuture handshakeFuture() { return handshakeFuture; } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { handshakeFuture = ctx.newPromise(); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { handshaker.handshake(ctx.channel()); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("WebSocket Client disconnected!"); } @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ctx.channel(), (FullHttpResponse) msg); System.out.println("WebSocket Client connected!"); handshakeFuture.setSuccess(); return; } if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } TextWebSocketFrame frame = (TextWebSocketFrame) msg; System.out.println("Received message: " + frame.text()); } } } ``` 这个示例代码启动了一个 WebSocket 服务器,监听本地的 8080 端口。当有新的 WebSocket 连接建立时,服务器会将连接加入到一个列表中,当有消息发送到服务器时,服务器会将消息转发给所有连接。同时,客户端与服务器建立连接,发送消息并接收服务器返回的消息。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值