netty5 客户端如何发信息给服务端??

刘大神仙 2017-09-21 09:40:10
现在的情况是,简单的客户端(TcpClient,TcpClientHandler两个类)和服务端代码都已经写好了,测试也通过了。但是客户端发信息时候,是通过main方法来来测试的,在实际应用中,比如我登录操作的controller类接收到了用户名和密码,现在要发送给服务端,那我的用户名和密码是怎么从controller类传到tcpclient类,然后发送给服务端的?

下面给出我的客户端代码:
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();
}

};
}
...全文
1814 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
pilnyun335857183 2017-09-22
  • 打赏
  • 举报
回复
做这种应用开发最头疼就是没有bean管理容器了。。。 你可以尝试在你的项目中集成spring,这样做难度也不大。如果觉得代价太大可以自己写个简单的单例类作为管理器 然后在其中创建login类的一个实例 同时提供get方法。
刘大神仙 2017-09-21
  • 打赏
  • 举报
回复
引用 1 楼 pilnyun335857183 的回复:
在你的TimerClient.connect中通过channelfuture拿到channel然后保存到全局对象里面就好了,channel.writeandflush可以写消息。
不好意思啊,才看到。。 试了这样做,可以的。现在还有一个问题,顺便请教一下哈~~~ 比如我的Login类里面的一个方法调用了channel.writeandflush将消息发送给服务器了,然后TimerClientHandler里面的channelRead方法收到服务器响应了,我现在怎么能将服务器的响应传递到Login类里面啊?
pilnyun335857183 2017-09-21
  • 打赏
  • 举报
回复
在你的TimerClient.connect中通过channelfuture拿到channel然后保存到全局对象里面就好了,channel.writeandflush可以写消息。

25,985

社区成员

发帖
与我相关
我的任务
社区描述
高性能WEB开发
社区管理员
  • 高性能WEB开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧