Netty初探-netty服务端和客户端demo

时间:2021-11-10 08:30:31

通过netty框架实现一个简单的服务端和客户端框架,相比于前面所说的NIO,netty的api使用更加简单灵活,扩展性强。

  • TimeServer
package com.xpn.netty.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class TimeServer {

public void bind(int port) throws InterruptedException {
// 配置NIO线程组
EventLoopGroup bossGroup = new NioEventLoopGroup();// 连接线程
EventLoopGroup workerGroup = new NioEventLoopGroup();// 处理线程组
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
bootstrap.childHandler(new ChildChannelHandler());
// 绑定端口,同步等待成功
ChannelFuture future = bootstrap.bind(port).sync();
// 等待服务端监听端口关闭,等待服务端链路关闭之后main函数才退出
future.channel().closeFuture().sync();
} finally {
// 优雅退出,释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}

}

private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeServerHandler());

}

}

public static void main(String[] args) throws InterruptedException {
int port = 8080;
if (args != null && args.length > 0) {
port = Integer.parseInt(args[0]);
}
new TimeServer().bind(port);

}

}
  • TimeClient
package com.xpn.netty.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class TimeClient {

/**
* @param args
*/

public static void main(String[] args) {
// TODO Auto-generated method stub
String host = "localhost";
int port = 8080;
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(workerGroup);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.handler(new ChannelInitializer<SocketChannel>() {

@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeClientHandler());

}
});
// 发起异步连接操作
ChannelFuture future = bootstrap.connect(host, port).sync();

future.channel().closeFuture().sync();
} catch (Exception e) {
workerGroup.shutdownGracefully();
}
}

}
  • TimeServerHandler
package com.xpn.netty.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.Date;

public class TimeServerHandler extends ChannelHandlerAdapter {

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
// TODO Auto-generated method stub
cause.printStackTrace();
ctx.close();
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];// 获得缓冲区可读的字节数
buf.readBytes(req);
String body = new String(req, "UTF-8");
System.out.println("the time server receive order : " + body);
String currentTime = "query time order".equalsIgnoreCase(body) ? new Date(
System.currentTimeMillis()).toString() : "bad order";
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.write(resp);// 性能考虑,仅将待发送的消息发送到缓冲数组中,再通过调用flush方法,写入channel中
}

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();// 将消息发送队列中的消息写入到SocketChannel中发送给对方。
}

}
  • TimeClientHandler
package com.xpn.netty.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.logging.Logger;

public class TimeClientHandler extends ChannelHandlerAdapter {

private static final Logger LOGGER = Logger
.getLogger(TimeClientHandler.class.getName());
private final ByteBuf firstMessage;

public TimeClientHandler() {
byte[] req = "query time order".getBytes();
firstMessage = Unpooled.buffer(req.length);
firstMessage.writeBytes(req);
}

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(firstMessage);// 将请求消息发送给服务端
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
LOGGER.warning("Unexpected exception from downstrema : "
+ cause.getMessage());
ctx.close();
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req, "UTF-8");
System.out.println("Now is : " + body);

}

}