Netty4实例入门

Netty4实例入门

建立两个maven模块Server和Client

maven项目导入

  • 注意这里要配置configuration,不然后面执行mvn exec:java会出错
    <dependencies>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.0.38.Final</version>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2</version>
                <configuration>
                   <mainClass>client.EchoClient</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

client模块下新建两个文件

EchoClient

public class EchoClient {

    private final String host;
    private final int port;

    public EchoClient(String host,int port) {
        this.host = host;
        this.port = port;
    }

    public static void main(String[] args)
            throws Exception {
        String host = "127.0.0.1";
        int port = 60296;
        new EchoClient(host,port).start();
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();                //1
            b.group(group)                                //2
                    .channel(NioSocketChannel.class)            //3
                    .remoteAddress(new InetSocketAddress(host, port))    //4
                    .handler(new ChannelInitializer<SocketChannel>() {    //5
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(
                                    new EchoClientHandler());
                        }
                    });

            ChannelFuture f = b.connect().sync();        //6

            f.channel().closeFuture().sync();            //7
        } finally {
            group.shutdownGracefully().sync();            //8
        }
    }
}

EchoClientHandler

@ChannelHandler.Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel Active!");
        ctx.writeAndFlush(Unpooled.copiedBuffer("Netty Worked", CharsetUtil.UTF_8));
    }

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

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
        System.out.println("Client Received:"+ ByteBufUtil.hexDump(byteBuf.readBytes(byteBuf.readableBytes())));
    }
}
    

在Server模块下新建两个文件

EchoServer

public class EchoServer {
    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args)
            throws Exception {
        // 服务器监听端口号
        int port = 60296;
        new EchoServer(port).start();
    }

    public void start() throws Exception {
        // NioEventLoopGroup是处理I/O操作的多线程事件循环
        NioEventLoopGroup  group = new NioEventLoopGroup();
        try {
            // ServerBootstrap是一个用于设置服务器的引导类。
            ServerBootstrap b = new ServerBootstrap();
            b.group(group)
                    .channel(NioServerSocketChannel.class) // 使用NioServerSocketChannel类,用于实例化新的通道以接受传入连接
                    .localAddress(new InetSocketAddress(port)) // 设置服务器监听端口号
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new EchoServerHandler()); // 添加请求处理
                        }
                    });
            // 绑定到端口和启动服务器
            ChannelFuture f = b.bind().sync();
            System.out.println(EchoServer.class.getName() +
                    " started and listening for connections on " + f.channel().localAddress());
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }
}

EchoSereverHandler

@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 覆盖channelRead()事件处理程序方法
        System.out.println("Server channelRead!");
        ByteBuf in = (ByteBuf) msg;
        System.out.println(
                "Server received: " + in.toString(CharsetUtil.UTF_8));
        ctx.write(in);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx)
            throws Exception {
        // channelRead()执行完成后,关闭channel连接
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                .addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,
                                Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
    

控制台执行

  • 在项目的根目录下执行mvn clean package
  • 在Server模块目录下执行 mvn exec:java
  • 在Client模块目录下执行 mvn exec:java

执行结果如下图所示:
在这里插入图片描述
在这里插入图片描述

推荐阅读

Netty实战精髓篇

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值