Netty实例

客户端可以主动的给服务端发送消息,服务端收到消息之后将消息打印到控制台上,然后将消息返回复给客户端

public class NettyClient {
    public static void main(String[] args) {
        EventLoopGroup worker = new NioEventLoopGroup(); 
        Bootstrap boot = new Bootstrap();// 客户端配置信息
        boot.group(worker)  // 绑定事件循环组
                .channel(NioSocketChannel.class) // 设置channel类型
                .handler(new ChannelInitializer<NioSocketChannel>() {   // 添加处理器
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new clientHandler())   // 给channel的pipeline上添加handler处理器     
                    }
                });
        try {
            //  获取建立连接的Channel通道,使用此通道主动发消息
            Channel channel = boot.connect("127.0.0.1", 8989).sync().channel();
            
            // 主动发送消息:
            Scanner scan = new Scanner(System.in);
            while (true) {
                String message = scan.nextLine();
                channel.writeAndFlush(Unpooled.copiedBuffer(message.getBytes()));
                System.out.println(message);
                if (message.equalsIgnoreCase("exit")) {
                    break;
                }
            }
            channel.closeFuture().sync();  // 关闭
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }
}

//回调函数类
class clientHandler extends ChannelInboundHandlerAdapter {
    // 只有当建立连接后执行一次
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接建立....);   
    }
    // 有读事件发生时执行
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        System.out.println("reading message...");
        ByteBuf readBuf = (ByteBuf) msg;
        System.out.println(readBuf.toString(CharsetUtil.UTF_8));

    }
    //有异常时执行
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("throw");
        cause.printStackTrace();
        ctx.close();
    }
}

服务端

public class NettyServer {
    public static void main(String[] args) {
        // 创建两个循环事件组
        EventLoopGroup boss = new NioEventLoopGroup();  // 处理接收
        EventLoopGroup worker = new NioEventLoopGroup(); // 处理接收之后的操作

        ServerBootstrap boot = new ServerBootstrap();     // 创建配置信息类
        boot.group(boss,worker )
                .channel(NioServerSocketChannel.class)  // 通过反射的手段,创建这个类的实例
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new serverHandler()) //添加自定义handler
                    }
                });

        try {
            ChannelFuture future = boot.bind(8989).sync();  // 绑定端口开始监听
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println("222");

            e.printStackTrace();
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}

//服务端回调函数
class serverHandler extends ChannelInboundHandlerAdapter {
  //有读事件发生时调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("333");
        System.out.println(">>>>>:"+msg);
        ByteBuf buf = (ByteBuf) msg;
        //打印收到的信息

        System.out.println(buf.toString(CharsetUtil.UTF_8));
        // 将收到的信息返回
        ctx.writeAndFlush(buf);
    }

// 连接建立时调用
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //ctx.fireChannelInactive();
        // 连接断开时调用
        System.out.println(ctx.channel().remoteAddress()+":上线");
    }
 // 连接断开时调用
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress()+":下线");
    }
    
    /**
     * @Description: 异常处理
     * @Param:  ctx 当前这个handler逻辑结束之后返回的对象
     * @return:  void
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过以下步骤在Spring Boot项目中引入Netty: 1. 在项目的pom.xml文件中添加Netty的依赖: ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.63.Final</version> </dependency> ``` 2. 创建一个Netty服务器类,例如 `NettyServer`: ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; public class NettyServer { private final int port; public NettyServer(int port) { this.port = port; } public void start() 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 { ch.pipeline().addLast(new YourNettyHandler()); } }); ChannelFuture future = bootstrap.bind(port).sync(); future.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } } ``` 3. 创建一个Netty处理器类,例如 `YourNettyHandler`,用于处理接收到的消息: ```java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class YourNettyHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 处理接收到的消息 ByteBuf byteBuf = (ByteBuf) msg; // TODO: 处理消息逻辑 byteBuf.release(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // 发生异常时的处理逻辑 cause.printStackTrace(); ctx.close(); } } ``` 4. 在Spring Boot应用的入口类中启动Netty服务器,例如 `Application`: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); // 启动Netty服务器 NettyServer server = new NettyServer(8080); server.start(); } } ``` 这样,你就可以在Spring Boot项目中成功引入并使用Netty了。请根据自己的需求进行相应的配置和修改。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值