Netty基于java nio(非阻塞) 实现,主要用于服务端与客户端之间的socket通信,其高性能号称单机可支持百万连接。其应用场景非常广泛,如物联网、分布式、聊天程序、网络游戏等。在基于java语言的项目中,要开发socket通信,netty目前几乎处于不可替代的地位。本篇将用netty实现一个简单的回声通信。
pom.xml
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.44.Final</version>
</dependency>
服务端
以下代码是官网的一个服务器启动示例,run方法里面是启动netty服务器的固定语法,具体什么意思先不讨论。只要知道其中有一个自定义类EchoServerHandler,需要自己实现,另外设置了服务端口8080。
public class EchoServer {
private int port;
public EchoServer(int port) {
this.port = port;
}
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap(); // (2)
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) // (3)
.childHandler(new ChannelInitializer<SocketChannel>() { // (4)
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128) // (5)
.childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
// Bind and start to accept incoming connections.
ChannelFuture f = b.bind(port).sync(); // (7)
// Wait until the server socket is closed.
// In this example, this does not happen, but you can do that to gracefully
// shut down your server.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port = 8080;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
}
new EchoServer(port).run();
}
}
实现消息回声
我们只需关注这个自定义类,它继承了输入适配器,只需覆盖channelRead方法即可接收消息。
public class EchoServerHandler extends ChannelInboundHandlerAdapter{
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ctx.writeAndFlush(msg);//将收到的消息原样返回, 即回声
}
- ChannelHandlerContext ctx:可用于对当前连接进行各种操作,比如这里回复消息。
- Object msg:就是客户端发过来的消息对象。
客户端
在现实中,客户端可能是一台自动售货机、快递柜、网游玩家、聊天室中的一员。也可能是微服务中的一个服务,通过netty来实现各服务之间的通信,比如阿里的dubbo就是这样做的。而客户端语言也不一定是java,也可能是c++、web前端、app等,只要支持socket连接,都可以作为客户端。为了快捷测试,可用任意socket或tcp相关工具软件模拟客户端,这里从网上下载SocketTool打开。TCP Client--创建
点击上面的连接按钮,连接按钮变成灰色说明连接成功
取消十六进制格式的勾选,输入hello,发送数据
发出数据hello,并且立即收到hello