首页 > 代码库 > netty入门代码学习

netty入门代码学习

服务端代码:

package com.lsp.netty;

/**
 * @author lishupeng
 * @create 2017-05-27 下午 3:48
 **/
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
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.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;


public class Socket {
    public static void main(String[] args) throws InterruptedException {
        //1.第一个线程组是用于接收Client端连接的
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //2.第二个线程组是用于实际的业务处理的
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);//绑定两个线程池
        b.channel(NioServerSocketChannel.class);//指定NIO的模式,如果是客户端就是NioSocketChannel
        b.option(ChannelOption.SO_BACKLOG, 1024);//TCP的缓冲区设置
        b.option(ChannelOption.SO_SNDBUF, 32*1024);//设置发送缓冲的大小
        b.option(ChannelOption.SO_RCVBUF, 32*1024);//设置接收缓冲区大小
        b.option(ChannelOption.SO_KEEPALIVE, true);//保持连续
        b.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel sc) throws Exception {
                ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());//拆包粘包定义结束字符串(第一种解决方案)
                sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,buf));//在管道中加入结束字符串
                //  sc.pipeline().addLast(new FixedLengthFrameDecoder(200));第二种定长
                sc.pipeline().addLast(new StringDecoder());//定义接收类型为字符串把ByteBuf转成String
                sc.pipeline().addLast(new ServertHandler());//在这里配置具体数据接收方法的处理
            }
        });
        ChannelFuture future = b.bind(8765).sync();//绑定端口
        future.channel().closeFuture().sync();//等待关闭(程序阻塞在这里等待客户端请求)
        bossGroup.shutdownGracefully();//关闭线程
        workerGroup.shutdownGracefully();//关闭线程
    }
}
package com.lsp.netty;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author lishupeng
 * @create 2017-05-27 下午 3:48
 **/
public class ServertHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String body = (String) msg;
        System.out.println("server"+body);//前面已经定义了接收为字符串,这里直接接收字符串就可以
        //服务端给客户端的响应
        String response= " hi client!$_";//发送的数据以定义结束的字符串结尾
        ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));//发送必须还是ByteBuf类型
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}

客户端代码:

package com.lsp.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
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;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @author lishupeng
 * @create 2017-05-27 下午 3:48
 **/
public class Client {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup worker = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(worker)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel sc) throws Exception {
                        ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());
                        sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,buf));
                        sc.pipeline().addLast(new StringDecoder());
                        sc.pipeline().addLast(new ClientHandler());
                    }
                });
        ChannelFuture f=b.connect("127.0.0.1",8765).sync();
        f.channel().writeAndFlush(Unpooled.copiedBuffer(" hi server2$_".getBytes()));
        f.channel().writeAndFlush(Unpooled.copiedBuffer(" hi server3$_".getBytes()));
        f.channel().writeAndFlush(Unpooled.copiedBuffer(" hi server4$_".getBytes()));
        f.channel().closeFuture().sync();
        worker.shutdownGracefully();
    }

}
package com.lsp.netty;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

/**
 * @author lishupeng
 * @create 2017-05-27 下午 3:49
 **/
public class ClientHandler extends ChannelHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            System.out.println("client"+msg.toString());
        } finally {
            ReferenceCountUtil.release(msg);//释放缓冲区
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

 

netty入门代码学习