netty hello world

来源:互联网 发布:c语言汉诺塔递归 编辑:程序博客网 时间:2024/05/29 11:39

入门文档

public class ServerHandler extends ChannelHandlerAdapter{


@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {
// ((ByteBuf) msg).release();
ByteBuf buf = (ByteBuf)msg;
byte[] data = new byte[buf.readableBytes()];
buf.readBytes(data);
String request = new String(data,"utf-8");
System.out.println("server:"+request);
//写给客户端
String response = "我是server反馈信息";
 ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
//  .addListener(ChannelFutureListener.CLOSE); 写完之后 客户端收到消息 就会关掉连接
// ctx.flush();
 
}


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



}

public class Server {

public static void main(String[] args) throws Exception {
//第一个线程组 接受client端
EventLoopGroup bossGroup = new NioEventLoopGroup(); 
//第二个线程组 实际业务处理
EventLoopGroup workerGroup = new NioEventLoopGroup();
//3 创建一个辅助类Bootstrap,就是对我们的Server进行一系列的配置
ServerBootstrap b = new ServerBootstrap();
//把两个工作线程组加进来
b.group(bossGroup, workerGroup)
//指定使用NioServerSocketChannel
.channel(NioServerSocketChannel.class)
//一定要使用 childHandler 去绑定具体的 事件处理器
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
sc.pipeline().addLast(new ServerHandler());//这里可以加多个处理器
}
});
 
//设置tcp的缓冲区
// .option(ChannelOption.SO_BACKLOG, 128)      
//保持连接
//     .option(ChannelOption.SO_KEEPALIVE, true);
 
//绑定指定端口 进行监听
ChannelFuture f = b.bind(8920).sync();
 
Thread.sleep(1000000);
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}


}


public class ClientHandler extends ChannelHandlerAdapter{


@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
try{
ByteBuf buf = (ByteBuf)msg;
byte[] data = new byte[buf.readableBytes()];
buf.readBytes(data);
String request = new String(data,"utf-8");
System.out.println("client:"+request);
} finally {
//没有调用write方法 需要手动释放
ReferenceCountUtil.release(msg);
}
}


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


}

public class Client {


public static void main(String[] args) throws Exception {
EventLoopGroup workGroup = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(workGroup)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {


@Override
protected void initChannel(SocketChannel sc) throws Exception {
sc.pipeline().addLast(new ClientHandler());
}
});

ChannelFuture f = b.connect("127.0.0.1",8920).sync();
 
//buf
f.channel().writeAndFlush(Unpooled.copiedBuffer("777".getBytes()));
// f.channel().flush();
 
f.channel().closeFuture().sync();
workGroup.shutdownGracefully(); 

}
}

原创粉丝点击