netty入门代码

服务器端代码

//创建服务器 
new ServerBootstrap()
//指定eventLoop分组
.group(new NioEventLoopGroup()) //指定channel实现 服务器选择NioServerSocketChannel
.channel(NioServerSocketChannel.class)
//添加处理器 当有客户端来连接时会调用 intiChannel方法
.childHandler(new ChannelInitializer<NioSocketChannel>() {
    protected void initChannel(NioSocketChannel nsc) throws Exception {
// 添加netty提供的StringDecode处理器 将ByteBuf对象转为String nsc.pipeline().addLast(new StringDecoder());
// 添加自己的入站处理器 拿到消息简单在控制台输出 nsc.pipeline().addLast(new ChannelInboundHandlerAdapter(){ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println(msg); } ); }
//绑定 8080端口 }).bind(8080);

 客户端代码

//启动客户端  指定eventLoop
new Bootstrap().group(new NioEventLoopGroup())
//指定channel实现客户端选择NioSocketChannel
.channel(NioSocketChannel.class)
//添加处理器
.handler(new ChannelInitializer<NioSocketChannel>() {
      @Override
      protected void initChannel(NioSocketChannel ch) throws Exception {
           //netty提供的StringEncoder
           ch.pipeline().addLast(new StringEncoder());
      }
}).connect(new InetSocketAddress("localhost", 8080))
//同步等待nio线程建立连接 同步方法
.sync()
//建立连接成功后获取channel向服务器发出数据
.channel().writeAndFlush("发送的数据");

  先启动服务器在启动客户端,服务器就会收到客户端发送的数据,netty的入门代码

posted @ 2022-05-16 16:48  wangkunlaile  阅读(98)  评论(0)    收藏  举报