netty------Helloworld

今天分享一下netty的helloworld,简单容易上手。
首先看server(注释已在代码中标明)

package com.netty.test;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class Server {
    
    public static void main(String[] args) throws InterruptedException {
        //用来接收客户端传进来的连接
        NioEventLoopGroup boss = new NioEventLoopGroup();
        //用来处理已被接收的连接
        NioEventLoopGroup work = new NioEventLoopGroup();
        //辅助类 用于帮助我们创建netty服务
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss, work)
        .channel(NioServerSocketChannel.class)//设置NIO模式
        .option(ChannelOption.SO_BACKLOG, 1024)//设置tcp缓冲区
        .childOption(ChannelOption.SO_SNDBUF, 32*1024)//设置发送缓冲区数据大小
        .option(ChannelOption.SO_RCVBUF, 32*1024)//设置接收缓冲区数据大小
        .childOption(ChannelOption.SO_KEEPALIVE, true)//保持长连接
        .childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                //通道的初始化,数据传输过来进行拦截及执行
                ch.pipeline().addLast(new ServerHandler());
                
            }
        });
        ChannelFuture f = serverBootstrap.bind(8888).sync();//绑定端口启动服务
        f.channel().closeFuture().sync();
        work.shutdownGracefully();
        boss.shutdownGracefully();


    }
    

}

接下来在看数据拦截的handler,这个里边主要是进行数据的处理。

package com.netty.test;

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

public class ServerHandler extends ChannelInboundHandlerAdapter{
    
    /**
     * 通道激活
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("数据激活");
    }
    
    /**
     * 通道数据读取
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf) msg;
        byte [] by = new byte [in.readableBytes()];
        in.readBytes(by);
        String body=new String(by,"utf-8");
        System.out.println("服务器收到数据:"+body);
        
        String response="进行返回给客户端的响应"+body;
        ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
    }
    
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("数据读取完毕");
    }
}

server端完成之后,接下来看客户端client,client代码和server端有点类似

package com.netty.test;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
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 Client {
    
    public static void main(String[] args) throws Exception {
        //server端不需要接收连接所有只用一个work来处理连接就可以。
        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
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ClientHandler());

                }
            });

            //连接
            ChannelFuture f = b.connect("127.0.0.1", 8888).sync();
            f.channel().writeAndFlush(Unpooled.copiedBuffer("hello word".getBytes()));
            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}

client的handler处理拦截数据,用来接收服务端返回的响应

package com.netty.test;

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

public class ClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    }
    
    /**
     * 通道数据读取
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf) msg;
        byte [] by = new byte [in.readableBytes()];
        in.readBytes(by);
        String body=new String(by,"utf-8");
        System.out.println("接收服务器端返回信息:"+body);
        
    }
    
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("接收返回信息完成");
    }
}

netty的helloworld就OK了,超级简单吧。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • netty常用API学习 netty简介 Netty是基于Java NIO的网络应用框架. Netty是一个NIO...
    花丶小伟阅读 6,044评论 0 20
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,269评论 25 708
  • 今天,哦不,昨晚我在看小美好的时候,你望了眼说了句:你们爱帅哥就像男人爱车一样! 听到这句话,我是想辩驳的,但是我...
    肥婉阅读 377评论 0 0
  • 点这里,音乐和文章更配哦~ 去年圣诞节,送给自己一台kindle,有人说,你买这个,浪费钱,手机一样可以看。今年圣...
    邢姑娘阅读 2,421评论 4 0