Netty学习记录(二)

Netty简单Demo

http://blog.youkuaiyun.com/hackxiaof/article/details/48474419

自己的练习代码

<dependency>
   <groupId>io.netty</groupId>
   <artifactId>netty-transport</artifactId>
   <version>5.0.0.Alpha1</version>
</dependency>
public class MyServer {
    public void start(int port) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChildChannelHandler());
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            System.out.println("服务启动");
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            System.out.println("服务器优雅的释放了线程资源...");
        }



    }


    private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new MySimpleServerHandle());
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8000;
        new MyServer().start(port);
    }
}
public class MySimpleServerHandle extends ChannelHandlerAdapter {
    private ByteBuf sendBuf;



    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf readByf = (ByteBuf) msg;
        byte[] req = new byte[readByf.readableBytes()];
        readByf.readBytes(req);
        String reqString = new String(req);
        System.out.println("服务端获取信息成功! [" + reqString + "]");
        //加密信息
        String respString = encryptByMD5(reqString);
        ByteBuf respByf = Unpooled.copiedBuffer(respString.getBytes());
        ctx.writeAndFlush(respByf);
        System.out.println("服务端响应数据成功! ["+respString+"]");
    }

    private String encryptByMD5(String reqString) {
        String result = "";
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            BASE64Encoder base64 = new BASE64Encoder();
            byte[] digest = md5.digest(reqString.getBytes());
            result = base64.encode(digest);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }


}
public class MyClient {

    public void connect(int port, String host) throws InterruptedException {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ClientHandler());

            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            channelFuture.channel().closeFuture().sync();

        } finally {
            group.shutdownGracefully();
            System.out.println("客户端优雅的释放了线程资源...");
        }

    }


    private class ClientHandler extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new MySimpleClientHandle());
        }
    }

    public static void main(String[] args) throws Exception {
        new MyClient().connect(8000, "127.0.0.1");

    }

}
public class MySimpleClientHandle extends ChannelHandlerAdapter {

    Random random = new Random();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String msg = String.valueOf(random.nextInt(1000));
        byte[] req = msg.getBytes();
        ByteBuf sendBuf = Unpooled.copiedBuffer(req);
        ctx.writeAndFlush(sendBuf);
        System.out.println("服务端发送信息成功! ");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf readBuf = (ByteBuf) msg;
        byte[] req = new byte[readBuf.readableBytes()];
        readBuf.readBytes(req);
        String readString = new String(req);
        System.out.println("客户端获取信息成功! ["+readString+"]");
    }
}

转载于:https://my.oschina.net/zhuqianli/blog/909403

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值