Netty 的 Hello World 案例分成两部分。一部分是服务端,将接收到的消息打印出来即可。另外一部分是客户端,发送消息。
服务端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| public class Server {
public static void main(String[] args) { EventLoopGroup boss = new NioEventLoopGroup(); EventLoopGroup worker = new NioEventLoopGroup(); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(boss, worker) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception { nioSocketChannel.pipeline() .addLast(new StringDecoder()) .addLast(new SimpleChannelInboundHandler<String>() { @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception { System.out.println("server 接收到的消息" + s); } }); } }); ChannelFuture channelFuture = serverBootstrap.bind("localhost", 8888); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { worker.shutdownGracefully(); boss.shutdownGracefully(); } }
}
|
EventLoopGroup
- 创建了两个反应器线程组,分别为
boss
和 worker
,boss
接收到请求后交由 worker
处理。
ServerBootstrap
- 服务端引导器,服务端引导器主要是为了进行一些配置,主要有以下配置。
- group 配置线程组
- channel 配置通道类型
- childHandler 配置一些 Handler
- 绑定的地址和端口
客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public class Client {
public static void main(String[] args) { EventLoopGroup worker = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); try { bootstrap.group(worker) .channel(NioSocketChannel.class) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new StringEncoder()); } }); ChannelFuture channelFuture = bootstrap.connect("localhost", 8888); Channel channel = channelFuture.channel(); while (true) { String msg = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + ": Hello world!!!"; channel.writeAndFlush(msg); TimeUnit.SECONDS.sleep(2); } } catch (InterruptedException e) { e.printStackTrace(); } finally { worker.shutdownGracefully(); } }
}
|
NioEventLoopGroup
- 在客户端,只有
worker
线程组,没有 boss
,只需要配置一个 worker
即可。
其余与 服务端
大致类似。
最终效果,客户端控制台无任何输出。服务端控制台,每隔两秒钟就会打印当前时间 + Hello Wold 的字样。