Netty学习笔记之引导程序

NioEventLoopGroup group = new NioEventLoopGroup();
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();
}
}
});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值