Netty服务器与客户端通讯案例

服务器端:



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;

public class NettyServer {
    public static void main(String[] args) throws InterruptedException {
        //1、创建两个线程组 bossGroup workGroup
//bossGroup线程组负责客户端连接
        EventLoopGroup bossGroup=new NioEventLoopGroup();
//workGroup线程组负责网络读写操作
        EventLoopGroup workGroup=new NioEventLoopGroup();
//2、创建服务器启动助手来配置参数--创建辅助的工具类,用于服务器通道的一些列配置
        ServerBootstrap serverBootstrap=new ServerBootstrap();
//链式编程
        serverBootstrap.group(bossGroup,workGroup)//绑定两个线程组
                .channel(NioServerSocketChannel.class)//指定NIO模式
                .option(ChannelOption.SO_BACKLOG,512)//设置TCP缓冲区
                .childOption(ChannelOption.SO_KEEPALIVE,true)//保持连接
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {//数据 接收方法的处理
                        ch.pipeline().addLast(new NettyServerHandler());//具体业务的处理
                    }
                });
        System.out.println("Server : 准备就绪!!!");
//3 绑定端口,设置非堵塞,,这里是一个异步操作
        ChannelFuture cf = serverBootstrap.bind(8765).sync();
        ChannelFuture cf2 = serverBootstrap.bind(8766).sync();//--绑定多个端口,开口变大,但是处理能力不变
        System.out.println("Server : 启动!!!");
//4 关闭通道
        cf.channel().closeFuture().sync();//等待关闭
        cf2.channel().closeFuture().sync();//等待关闭
        System.out.println("Server--关闭通道!!!");
//关闭线程组
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
        System.out.println("Server--关闭线程组!!!");
    }
}


服务器业务处理类:


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import javax.sound.midi.Soundbank;

//普通类变成业务处理类需要继承一个类或者实现一个接口
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    //数据的读取事件
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws
            Exception {
        System.out.println("serverHandler--ctx:"+ctx);
        ByteBuf buffer= (ByteBuf) msg;
        System.out.println("来自客户端的消息:"+buffer.toString(CharsetUtil.UTF_8));
    }
    //数据读取完毕事件
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception
    {
        ChannelFuture channelFuture =
                ctx.writeAndFlush(Unpooled.copiedBuffer("hi,client,我收到你的消息啦!", CharsetUtil.UTF_8));
//添加监听事件:数据发送完毕之后,直接断开客户端的连接
       // channelFuture.addListener(ChannelFutureListener.CLOSE);
    }
    //异常捕捉事件
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        ctx.close();
    }
}

客户端:



import io.netty.bootstrap.Bootstrap;
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.NioSocketChannel;

public class NettyClient {
    public void run() throws InterruptedException {
        EventLoopGroup group=new NioEventLoopGroup();
//创建客户端的启动助手
        Bootstrap bootstrap=new Bootstrap();
//开始配置
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws
                            Exception {
                        ch.pipeline().addLast(new NettyClientHandler());//具体业务处理
                    }
                });
        System.out.println("Client: 准备就绪!!!");
//启动客户端去连接服务器
        ChannelFuture cf = bootstrap.connect("127.0.0.1", 8765).sync();
        ChannelFuture cf2 = bootstrap.connect("127.0.0.1", 8766).sync();
        //服务器端断开连接这边才会断开连接的,
        cf.channel().closeFuture().sync();//等待关闭
        cf2.channel().closeFuture().sync();//等待关闭
        System.out.println("Client--关闭通道!!!");
        group.shutdownGracefully();
        System.out.println("Client--关闭线程组!!!");
    }
    public static void main(String[] args) {
        try {
            new NettyClient().run();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

客户端业务处理类:


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

//客户端业务处理类
//入站操作,进入pipeline里面
public class NettyClientHandler extends ChannelInboundHandlerAdapter{
    //通道就绪
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Client: ctx="+ctx);
        ctx.writeAndFlush(Unpooled.copiedBuffer("hi,server,这是来自客户端的招呼!", CharsetUtil.UTF_8));
    }
    //数据的读取事件
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws
            Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("服务器回复的消息:" + buf.toString(CharsetUtil.UTF_8));
    }
}


在这里插入图片描述
在这里插入图片描述
当服务器断开以后,客户端会执行断开连接的操作。
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凌晨里的无聊人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值