Java Nio Netty

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Dopamy_BusyMonkey/article/details/82735608

https://blog.csdn.net/zzy7075/article/details/52095852

1、SimpleServer

import io.netty.bootstrap.ServerBootstrap;  
import io.netty.channel.ChannelFuture;  
import io.netty.channel.ChannelInitializer;  
import io.netty.channel.ChannelOption;  
import io.netty.channel.EventLoopGroup;  
import io.netty.channel.nio.NioEventLoopGroup;  
import io.netty.channel.socket.SocketChannel;  
import io.netty.channel.socket.nio.NioServerSocketChannel;  
  
/** 
 *  
 * Netty中,通讯的双方建立连接后,会把数据按照ByteBuf的方式进行传输, 
 * 例如http协议中,就是通过HttpRequestDecoder对ByteBuf数据流进行处理,转换成http的对象。 
 *  
 */  
public class SimpleServer {  
    private int port;  
  
    public SimpleServer(int port) {  
        this.port = port;  
    }  
  
    public void run() throws Exception {  
        //EventLoopGroup是用来处理IO操作的多线程事件循环器  
        //bossGroup 用来接收进来的连接  
        EventLoopGroup bossGroup = new NioEventLoopGroup();   
        //workerGroup 用来处理已经被接收的连接  
        EventLoopGroup workerGroup = new NioEventLoopGroup();  
        try {  
            //启动 NIO 服务的辅助启动类  
            ServerBootstrap b = new ServerBootstrap();   
            b.group(bossGroup, workerGroup)  
                //配置 Channel  
                .channel(NioServerSocketChannel.class)  
                .childHandler(new ChannelInitializer<SocketChannel>() {   
                        @Override  
                        public void initChannel(SocketChannel ch) throws Exception {  
                            // 注册handler    
                            ch.pipeline().addLast(new SimpleServerHandler());  
                        }  
                    })  
                .option(ChannelOption.SO_BACKLOG, 128)   
                .childOption(ChannelOption.SO_KEEPALIVE, true);   
  
            // 绑定端口,开始接收进来的连接  
            ChannelFuture f = b.bind(port).sync();  
            // 等待服务器 socket 关闭 。  
            f.channel().closeFuture().sync();  
        } finally {  
            workerGroup.shutdownGracefully();  
            bossGroup.shutdownGracefully();  
        }  
    }  
      
    public static void main(String[] args) throws Exception {  
        new SimpleServer(9999).run();  
    }  
}  

2、SimpleServerHandler

import io.netty.buffer.ByteBuf;  
import io.netty.channel.ChannelHandlerContext;  
import io.netty.channel.ChannelInboundHandlerAdapter;  
  
public class SimpleServerHandler extends ChannelInboundHandlerAdapter {  
  
    @Override  
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {  
        System.out.println("SimpleServerHandler.channelRead");  
        ByteBuf result = (ByteBuf) msg;  
        byte[] result1 = new byte[result.readableBytes()];  
        // msg中存储的是ByteBuf类型的数据,把数据读取到byte[]中  
        result.readBytes(result1);  
        String resultStr = new String(result1);  
        // 接收并打印客户端的信息  
        System.out.println("Client said:" + resultStr);  
        // 释放资源,这行很关键  
        result.release();  
        // 向客户端发送消息  
        String response = "hello client!";  
        // 在当前场景下,发送的数据必须转换成ByteBuf数组  
        ByteBuf encoded = ctx.alloc().buffer(4 * response.length());  
        encoded.writeBytes(response.getBytes());  
        ctx.write(encoded);  
        ctx.flush();  
    }  
  
    @Override  
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {  
        // 当出现异常就关闭连接  
        cause.printStackTrace();  
        ctx.close();  
    }  
  
    @Override  
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {  
        ctx.flush();  
    }  
}  

3、SimpleClient

import io.netty.bootstrap.Bootstrap;  
import io.netty.channel.ChannelFuture;  
import io.netty.channel.ChannelInitializer;  
import io.netty.channel.ChannelOption;  
import io.netty.channel.EventLoopGroup;  
import io.netty.channel.nio.NioEventLoopGroup;  
import io.netty.channel.socket.SocketChannel;  
import io.netty.channel.socket.nio.NioSocketChannel;  
  
public class SimpleClient {  
      
    public void connect(String host, int port) throws Exception {  
        EventLoopGroup workerGroup = new NioEventLoopGroup();  
        try {  
            Bootstrap b = new Bootstrap();  
            b.group(workerGroup);  
            b.channel(NioSocketChannel.class);  
            b.option(ChannelOption.SO_KEEPALIVE, true);  
            b.handler(new ChannelInitializer<SocketChannel>() {  
                @Override  
                public void initChannel(SocketChannel ch) throws Exception {  
                    ch.pipeline().addLast(new SimpleClientHandler());  
                }  
            });  
  
            ChannelFuture f = b.connect(host, port).sync();  
            f.channel().closeFuture().sync();  
        } finally {  
            workerGroup.shutdownGracefully();  
        }  
    }  
      
    public static void main(String[] args) throws Exception {  
        SimpleClient client=new SimpleClient();  
        client.connect("127.0.0.1", 9999);  
    }  
}  

4、SimpleClientHandler

import io.netty.buffer.ByteBuf;  
import io.netty.channel.ChannelHandlerContext;  
import io.netty.channel.ChannelInboundHandlerAdapter;  
  
public class SimpleClientHandler extends ChannelInboundHandlerAdapter {  
  
    @Override  
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {  
        System.out.println("SimpleClientHandler.channelRead");    
        ByteBuf result = (ByteBuf) msg;    
        byte[] result1 = new byte[result.readableBytes()];    
        result.readBytes(result1);    
        System.out.println("Server said:" + new String(result1));    
        result.release();    
    }  
  
    @Override  
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {  
        cause.printStackTrace();  
        ctx.close();  
    }  
  
    // 连接成功后,向server发送消息    
    @Override    
    public void channelActive(ChannelHandlerContext ctx) throws Exception {    
        String msg = "hello Server!";    
        ByteBuf encoded = ctx.alloc().buffer(4 * msg.length());    
        encoded.writeBytes(msg.getBytes());    
        ctx.write(encoded);    
        ctx.flush();    
    }    
}  

5、EventLoopGroup

6、NioEventLoopGroup

7、ServerBootstrap

8、ChannelFuture

9、ChannelInboundHandlerAdapter

猜你喜欢

转载自blog.csdn.net/Dopamy_BusyMonkey/article/details/82735608