新学Netty,编译运行时踩了一些坑,记录在此。
essential netty in action中有一个入门demo,EchoServer and EchoClient,用于Netty入门的小demo。
(Essential Netty in Action)
EchoClient主要功能
1、启动客户端,发起连接
public class Client {
private final String host;
private final int port;
public Client(String host, int port) {
this.host = host;
this.port = port;
}
public void start() throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try{
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress(host,port))
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ch.pipeline().addLast(new ClientHandler());
}
});
ChannelFuture f = b.connect().sync();
f.channel().closeFuture().sync();
}finally {
group.shutdownGracefully().sync();
}
}
public static void main(String[] args) throws Exception {
if(args.length != 2){
System.err.println(
"Usage :" + Client.class.getSimpleName()+
"<host><port>"
);
return;
}
final String host = args[0];
final int port = Integer.parseInt(args[1]);
new Client(host,port).start();
}
}
2、ClientHandler处理返回到客户端的数据
class ClientHandler extends SimpleChannelInboundHandler<ByteBuf>{
@Override
public void channelActive(ChannelHandlerContext ctx){
ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!",CharsetUtil.UTF_8));
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
System.out.println("Client received: "+in.toString(CharsetUtil.UTF_8));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
EchoServer主要功能
1、启动服务端,监听连接请求
public class EchoServer {
public void bind(int port) throws Exception {