一个简单的POJO netty客户端和服务端例子
程序员文章站
2022-06-06 12:07:44
...
一个简单的POJO netty客户端和服务端例子
这是一个参考netty官网写的,做了一些改变
版本
代码地址 netty-hello-world
POJO
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.42.Final</version>
</dependency>
public class UnixTime {
private final long value;
public UnixTime() {
this(System.currentTimeMillis() / 1000L + 2208988800L);
}
public UnixTime(long value) {
this.value = value;
}
public long value() {
return value;
}
@Override
public String toString() {
return new Date((value() - 2208988800L) * 1000L).toString();
}
}
解码和编码器
public class TimeDecoder extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
if (byteBuf.readableBytes() < 4) {
return;
}
list.add(new UnixTime(byteBuf.readUnsignedInt()));
}
}
public class TimeEncoder extends MessageToByteEncoder<UnixTime> {
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, UnixTime unixTime, ByteBuf byteBuf) throws Exception {
byteBuf.writeInt((int) unixTime.value());
}
}
服务端handler
public class TimeServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
UnixTime time = new UnixTime();
ctx.writeAndFlush(time);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
UnixTime time = (UnixTime) msg;
System.out.println("接受到客户端数据:" + time.toString());
TimeUnit.SECONDS.sleep(2);
ctx.writeAndFlush(new UnixTime());
}
}
服务主方法
public class DiscardServer {
private int port;
public DiscardServer(int port) {
this.port = port;
}
public static void main(String[] args) throws Exception {
int port = 9090;
new DiscardServer(port)
.run();
}
public void run() throws Exception {
//第一个BossGroup是用来处理进来的链接
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline()
.addLast(new TimeEncoder())
.addLast(new TimeDecoder())
.addLast(new TimeServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture channelFuture = b.bind(port)
.sync();
channelFuture.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
客户端
public class TimeClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
UnixTime m = (UnixTime) msg;
System.out.println("接受到服务端数据:" + m.toString());
TimeUnit.SECONDS.sleep(2);
ctx.writeAndFlush(new UnixTime());
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
UnixTime time = new UnixTime();
ctx.writeAndFlush(time);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
客户端主方法
public class TimeClient {
public static void main(String[] args) throws Exception {
String host = "127.0.0.1";
int port = 9090;
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap(); // (1)
b.group(workerGroup); // (2)
b.channel(NioSocketChannel.class); // (3)
b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
.addLast(new TimeDecoder())
.addLast(new TimeEncoder())
.addLast(new TimeClientHandler());
}
});
// Start the client.
ChannelFuture f = b.connect(host, port).sync(); // (5)
// Wait until the connection is closed.
f.channel().closeFuture().sync();
f.channel().writeAndFlush(new UnixTime());
} finally {
workerGroup.shutdownGracefully();
}
}
}
上一篇: java多线程通信(服务器与多客户端)
下一篇: TCP客户端和服务端的程序开发流程