在篇1中,写了一个抛弃服务,可以使用telnet
命令来测试它是否真的可以运行,telnet
可以测试本机到某个IP+端口的网络是否畅通,即对方的服务器是否在这个端口上提供了服务。虽然可以用telnet
检测到它正在运行,但是抛弃服务把收到的所有请求都忽略了,难以说明是否在正常运行。
现在通过写一个应答服务,来看看服务是否正常运行了。应答服务采用ECHO
协议,这个协议会把任何接收的数据都原样返回。
1. EchoServer
public class EchoServer {
private int port = 8080;
public EchoServer(int port) {
this.port = port;
}
public void run() throws InterruptedException {
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup worker = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(boss, worker)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new EchoServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture future = serverBootstrap.bind(port).sync();
future.channel().closeFuture().sync();
} finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
public static void main(String[] args) {
try {
new EchoServer(8080).run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
复制代码
EchoServer
的实现与篇1中的抛弃服务实现是一样的,只是把pipeline中添加的服务Handler换成了EchoServerHandler
,pipeline的意思就是管道,流水线。addLast()
方法就相当于在流水线的最后加入了一道工序对channel中的数据进行处理。
2. EchoServerHandler
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 写入的时候netty会释放消息
ctx.write(msg);
ctx.flush();
}
}
复制代码
EchoServerHandler
继承自ChannelInboundHandlerAdapter
,ChannelInboundHandlerAdapter
会拦截入站的各种I/O事件,channelReader
就是一个I/O事件回调方法,当Channel可以从远端读取到数据时它会触发。
ctx.write(msg);
将消息写入到缓冲区,flush()
将缓冲区的消息刷新到Channel中。要注意的是,这里我们并未手动释放消息,这是因为调用write()
的时候Netty已经帮我们释放了。也可以使用cxt.writeAndFlush(msg)
来达到相同的目的。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END