Android端采用Netty实现长连接通信
最近项目需要使用TCP/IP协议和服务器进行长连接通信,在网上找了些关于Android 网络通信的框架但是大部分都是采用http的请求框架并不能够满足需求,最后没有办法就只能够自己尝试采用java中使用的Netty框架来实现该功能。
Netty框架Jar包使用
在项目中我使用的是4.0的jar包如有需要可联系也可自行下载
netty-all-4.0.36.Final.jar
Netty客户端的编写
第一步:创建NettyClient类
public class NettyClient {
public static final int DISCONNECTION = 0;
public static final int CONNECTING = 1;
public static final int CONNECTED = 2;
private EventLoopGroup group = null;
private Bootstrap bootstrap = null;
private ChannelFuture channelFuture = null;
private static NettyClient nettyClient = null;
private ArrayBlockingQueue<String> sendQueue = new ArrayBlockingQueue<String>(5000);
private boolean sendFlag = true;
private SendThread sendThread = new SendThread();
private int connectState = DISCONNECTION;
private boolean flag = true;
public static NettyClient getInstance() {
if (nettyClient == null) {
nettyClient = new NettyClient();
}
return nettyClient;
}
private NettyClient() {
init();
}
private void init() {
setConnectState(DISCONNECTION);
bootstrap = new Bootstrap();
group = new