25,985
社区成员
发帖
与我相关
我的任务
分享
public class TimerClient {
public static void main(String[] args) {
TimerClient t = new TimerClient();
t.connect(8125, "localhost");
}
public void connect(int port,String host){
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.TCP_NODELAY, true);
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ObjectDecoder(1024*1024,
ClassResolvers.cacheDisabled(this.getClass().getClassLoader())));
ch.pipeline().addLast(new ObjectEncoder());
ch.pipeline().addLast(new TimerClientHandler());
}
});
try {
ChannelFuture cf = bootstrap.connect(host, port).sync();
cf.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
group.shutdownGracefully();
}
}
}
public class TimerClientHandler extends ChannelHandlerAdapter{
private static final Logger logger = Logger.getLogger(TimerClientHandler.class.getName());
/**
* 发送消息给服务端
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
Event even = new Event();
even.setEventId(1);
QueryTime qt = new QueryTime();
qt.setName("时间23");
even.setJsonObject(JSONObject.toJSONString(qt));
ctx.writeAndFlush(even);
}
/**
* 接收服务端返回的信息
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
QueryTimeVo vo = (QueryTimeVo)msg;
if(vo.isSuccess()){
System.out.println(vo.getName()+":"+vo.getTime());
}else{
System.out.println("读取失败!");
}
} catch (Exception e) {
e.printStackTrace();
}
};
}