ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(group)//设置ServerBootstrap要用的EventLoopGroup。这个EventL哦哦破Group将用于ServerChannel和被接受的子Channel的I/O处理
.channel(NioServerSocketChannel.class) //设置将要被实例化的ServerChannel类
.childHandler(new SimpleChannelInboundHandler<ByteBuf>(){//此方法添加的ChannelHandler将由已经
@Override
protected void messageReceived(ChannelHandlerContext ctx,ByteBuf msg) throws Exception {
System.out.println("Data");
}
});
ChannelFuture future = bootstrap.bind(new InetSocketAddress(8080));
future.addListener(new ChannelFutureListener (){
@Override
public void operationComplete(ChannelFuture channelFuture)throws Exception {
if (channelFuture.isSuccess()) {
System.out.println("Server bound");
} else {
System.out.println("Bound attemt failed");
channelFuture.cause().printStackTrace();
}
}
});
引导服务器:代码清单
ServerBootstrap bootstrap = new ServerBootstrap();//创建ServerBootstrap 以创建ServerSocketChannel,并绑定它
bootstrap.group(new NioEventLoopGroup(),new NioEventLoopGroup())//设置EventLoopGroup,其将提供用以处理Channel事件的EventLoop
.channel(NioServerSocketChannel.class)//指定要使用的Channel实现
.childHandler(//设置用于处理已被接受的子Channel的IO和数据的ChannelInboundHandler
new SimpleChannelInboundHandler<ByteBuf>() {
ChannelFuture connectFuture;
@Override
protected void messageReceived(ChannelHandlerContext channelHandlerContext,ByteBuf byteBuf) throws Exception {
if (connectFuture.isDone()) {//当连接完成时,执行相关的数据操作
// do something with the data;
}
}
@Override
public void channelActive(ChannelHandlerContext ctx)throws Exception {
Bootstrap bootstrap = new Bootstrap();//创建一个 Bootstrap类的实例,以连接到远程主机
bootstrap.channel(NioSocketChannel.class)//指定Channel的实现
.handler(
new SimpleChannelInboundHandler<ByteBuf>(){//为入站IO设置ChannelInboundHandler
@Override
protected void messageReceived(
ChannelHandlerContext ctx, ByteBuf in)throws Exception {
System.out.println("Received data");
}
});
bootstrap.group(ctx.channel().eventLoop());//使用与分配给已被接受的子Channel相同的EventLoop
connectFuture = bootstrap.connect(new InetSocketAddress("www.maning.com",8080));//连接到远程节点
}
});
ChannelFuture future = bootstrap.bind(new InetSocketAddress(8080));//通过配置好的ServerBootstrap绑定该ServerSocketChannel
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
if (channelFuture.isSuccess()) {
System.out.println("Server bound");
} else {
System.err.println("Bind attempt failed");
channelFuture.cause().printStackTrace();
}
}
});