基于Apache mina 的android 客户端tcp长连接实现

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

                       

TCP-long-connection-based-on-Apache-mina

基于Apache mina 的tcp长连接实现,可用于android客户端推送。

项目Github地址:https://github.com/sddyljsx/Android-tcp-long-connection-based-on-Apache-mina

项目将Apache的mina项目移植到了android平台。实现长连接的主要思想是使用了mina的KeepAliveFilter过滤器。

acceptor.getFilterChain().addLast("keeplive", new KeepAliveFilter(new ServerKeepAliveMessageFactoryImp(), IdleStatus.READER_IDLE, KeepAliveRequestTimeoutHandler.CLOSE,10, 5));
   
   
  • 1

Android客户端:

核心代码如下图所示,规定了长连接ping与pong信息的规则,以及网络参数配置信息。

配置信息:

/** * 服务器地址 */public static final String HOSTNAME = "192.168.1.15";/** * 服务器端口号 */public static final int PORT = 8081;/** * 连接超时时间,30 seconds */public static final long SOCKET_CONNECT_TIMEOUT = 30 * 1000L;/** * 长连接心跳包发送频率,10 seconds */public static final int KEEP_ALIVE_TIME_INTERVAL = 10;/** * 长连接心跳包应答超时 */public static final int KEEP_ALIVE_RESPONSE_TIMEOUT = 5;/** * 心跳包 ping message */public static final String PING_MESSAGE="ping";/** * 心跳包 pong message */public static final String PONG_MESSAGE="pong";
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

程序启动后,PushService启动,并开始与服务器连接。

服务器端核心代码:

服务器与客户端的ping与pong信息要保持一致。服务器启动LongTcpServer即可。

在服务器可以看到日志信息:

可以看到,成功建立了链接,并且每隔10秒都会受到ping信息,并发送pong信息应答。

           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/hfuuhgcc/article/details/84195798