Netty5入門(2),netty5入門
四、Time協議
繼續測試《netty5使用者指南》中的Time協議。
1、一個封裝時間的特殊的POJO類
首先實現UnixTime類:
package com.ydtf;
import java.util.Date;
public class UnixTime {
private final int value;
public UnixTime() {
this((int) (System.currentTimeMillis() / 1000L+ 2208988800L));
}
public UnixTime(int value) {
this.value = value;
}
public int value() {
return value;
}
@Override
public String toString() {
return new Date((value() - 2208988800L) *1000L).toString();
}
}
2、將ByteBuf轉換為POJO
然後是TimeDecoder類:
package com.ydtf;
import java.util.List;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
public class TimeDecoder extends ByteToMessageDecoder { // (1)
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in,
List<Object>out) throws Exception {
if (in.readableBytes()< 4) {
return;
}
out.add(new UnixTime(in.readInt()));
}
}
3、將POJO轉換為ByteBuf
TimeEncoder,用於進行UnixTime –>ByteBuf的轉換。
package com.ydtf;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
public class TimeEncoder extends MessageToByteEncoder<UnixTime> {
@Override
protected void encode(ChannelHandlerContext ctx, UnixTime msg, ByteBuf out)
throws Exception {
out.writeInt(msg.value());
}
}
4、服務端的處理
然後是服務端的handler:
package com.ydtf;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public classTimeServerHandler extendsChannelHandlerAdapter {
@Override
public voidchannelActive(ChannelHandlerContext ctx) {
ChannelFuture f = ctx.writeAndFlush(new UnixTime());
f.addListener(ChannelFutureListener.CLOSE);
}
@Override
public voidexceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
5、用戶端的處理
用戶端的handler:
package com.ydtf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public classTimeClientHandler extendsChannelHandlerAdapter {
@Override
public voidchannelRead(ChannelHandlerContext ctx, Object msg) {
UnixTime m = (UnixTime) msg;
System.out.println(m);
ctx.close();
}
@Override
public voidexceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
6、服務端主類
package com.ydtf;
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;
importio.netty.channel.socket.nio.NioServerSocketChannel;
public class TimeServer {
private int port;
public TimeServer(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(newChannelInitializer<SocketChannel>() { // (4)
@Override
public voidinitChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeEncoder(), new TimeServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128) // (5)
.childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
ChannelFuture f = b.bind(port).sync(); // (7)
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 8080;
}
new TimeServer(port).run();
}
}
7、用戶端主類
packagecom.ydtf;
importio.netty.bootstrap.Bootstrap;
importio.netty.channel.ChannelFuture;
importio.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
importio.netty.channel.EventLoopGroup;
importio.netty.channel.nio.NioEventLoopGroup;
importio.netty.channel.socket.SocketChannel;
importio.netty.channel.socket.nio.NioSocketChannel;
publicclass TimeClient {
public static void main(String[] args)throws Exception {
String host = args[0];
int port = Integer.parseInt(args[1]);
EventLoopGroup workerGroup = newNioEventLoopGroup();
try {
Bootstrap b = new Bootstrap(); //(1)
b.group(workerGroup); // (2)
b.channel(NioSocketChannel.class);// (3)
b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
b.handler(newChannelInitializer<SocketChannel>() {
@Override
public voidinitChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(newTimeDecoder(), new TimeClientHandler());
}
});
// Start the client.
ChannelFuture f = b.connect(host,port).sync(); // (5)
// Wait until the connection isclosed.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
}
8、運行
在TimeServer.java上右鍵,Run as >> Java Application,啟動服務端。
然後在TimeClient.java上右鍵,Run as >> Run Configurations…,在彈出的視窗中設定Name和Main Class:
Name設定一個和現有配置不重複的就可以了,比如TimeClient1、TimeClien(2)等。點擊Mainclass右邊的Search…按鈕,選擇TimeClient類。
然後點Arguments,添加兩個運行參數localhost和8080:
然後點擊視窗右下角的Run按鈕。這是你將在用戶端的Console視窗中看見一個日期輸出。
如果想分別查看服務端和用戶端的Console輸出,請點擊Display Selected Console按鈕: