Update CIMConnectorManager.java

This commit is contained in:
远方夕阳 2014-09-04 15:16:56 +08:00
parent deecd2f4e7
commit b0f2befd45

View File

@ -1,300 +1,310 @@
package com.farsunset.cim.client.android; package com.farsunset.cim.client.android;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.WriteCompletionEvent; import org.jboss.netty.channel.WriteCompletionEvent;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.net.ConnectivityManager; import android.net.ConnectivityManager;
import android.net.NetworkInfo; import android.net.NetworkInfo;
import com.farsunset.cim.nio.filter.ClientMessageDecoder; import com.farsunset.cim.nio.filter.ClientMessageDecoder;
import com.farsunset.cim.nio.filter.ClientMessageEncoder; import com.farsunset.cim.nio.filter.ClientMessageEncoder;
import com.farsunset.cim.nio.mutual.Message; import com.farsunset.cim.nio.mutual.Message;
import com.farsunset.cim.nio.mutual.ReplyBody; import com.farsunset.cim.nio.mutual.ReplyBody;
import com.farsunset.cim.nio.mutual.SentBody; import com.farsunset.cim.nio.mutual.SentBody;
/** /**
* 连接服务端管理cim核心处理类管理连接以及消息处理 * 连接服务端管理cim核心处理类管理连接以及消息处理
* *
* @author 3979434@qq.com * @author 3979434@qq.com
*/ */
class CIMConnectorManager { class CIMConnectorManager {
private Channel channel;; private Channel channel;;
Context context; Context context;
ClientBootstrap bootstrap; ClientBootstrap bootstrap;
static CIMConnectorManager manager; static CIMConnectorManager manager;
// 消息广播action // 消息广播action
public static final String ACTION_MESSAGE_RECEIVED = "com.farsunset.cim.MESSAGE_RECEIVED"; public static final String ACTION_MESSAGE_RECEIVED = "com.farsunset.cim.MESSAGE_RECEIVED";
// 发送sendbody失败广播 // 发送sendbody失败广播
public static final String ACTION_SENT_FAILED = "com.farsunset.cim.SENT_FAILED"; public static final String ACTION_SENT_FAILED = "com.farsunset.cim.SENT_FAILED";
// 发送sendbody成功广播 // 发送sendbody成功广播
public static final String ACTION_SENT_SUCCESS = "com.farsunset.cim.SENT_SUCCESS"; public static final String ACTION_SENT_SUCCESS = "com.farsunset.cim.SENT_SUCCESS";
// 链接意外关闭广播 // 链接意外关闭广播
public static final String ACTION_CONNECTION_CLOSED = "com.farsunset.cim.CONNECTION_CLOSED"; public static final String ACTION_CONNECTION_CLOSED = "com.farsunset.cim.CONNECTION_CLOSED";
// 链接失败广播 // 链接失败广播
public static final String ACTION_CONNECTION_FAILED = "com.farsunset.cim.CONNECTION_FAILED"; public static final String ACTION_CONNECTION_FAILED = "com.farsunset.cim.CONNECTION_FAILED";
// 链接成功广播 // 链接成功广播
public static final String ACTION_CONNECTION_SUCCESS = "com.farsunset.cim.CONNECTION_SUCCESS"; public static final String ACTION_CONNECTION_SUCCESS = "com.farsunset.cim.CONNECTION_SUCCESS";
// 发送sendbody成功后获得replaybody回应广播 // 发送sendbody成功后获得replaybody回应广播
public static final String ACTION_REPLY_RECEIVED = "com.farsunset.cim.REPLY_RECEIVED"; public static final String ACTION_REPLY_RECEIVED = "com.farsunset.cim.REPLY_RECEIVED";
// 网络变化广播 // 网络变化广播
public static final String ACTION_NETWORK_CHANGED = "android.net.conn.CONNECTIVITY_CHANGE"; public static final String ACTION_NETWORK_CHANGED = "android.net.conn.CONNECTIVITY_CHANGE";
// 未知异常 // 未知异常
public static final String ACTION_UNCAUGHT_EXCEPTION = "com.farsunset.cim.UNCAUGHT_EXCEPTION"; public static final String ACTION_UNCAUGHT_EXCEPTION = "com.farsunset.cim.UNCAUGHT_EXCEPTION";
// CIM连接状态 // CIM连接状态
public static final String ACTION_CONNECTION_STATUS = "com.farsunset.cim.CONNECTION_STATUS"; public static final String ACTION_CONNECTION_STATUS = "com.farsunset.cim.CONNECTION_STATUS";
private ExecutorService executor; private ExecutorService executor;
private CIMConnectorManager(Context ctx) { private CIMConnectorManager(Context ctx) {
context = ctx; context = ctx;
executor = Executors.newFixedThreadPool(3); executor = Executors.newFixedThreadPool(3);
bootstrap = new ClientBootstrap( bootstrap = new ClientBootstrap(
new NioClientSocketChannelFactory( new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(), Executors.newCachedThreadPool(),
Executors.newCachedThreadPool())); Executors.newCachedThreadPool()));
bootstrap.setPipelineFactory(new ChannelPipelineFactory() { bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception { public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline( return Channels.pipeline(
new ClientMessageDecoder(), new ClientMessageDecoder(),
new ClientMessageEncoder(), new ClientMessageEncoder(),
channelUpstreamHandler); channelUpstreamHandler);
} }
}); });
} }
public synchronized static CIMConnectorManager getManager(Context context) { public synchronized static CIMConnectorManager getManager(Context context) {
if (manager == null) { if (manager == null) {
manager = new CIMConnectorManager(context); manager = new CIMConnectorManager(context);
} }
return manager; return manager;
} }
private synchronized void syncConnection(final String cimServerHost,final int cimServerPort) { private synchronized void syncConnection(final String cimServerHost,final int cimServerPort) {
try { try {
if(isConnected()){ if(isConnected()){
return ; return ;
} }
channel = bootstrap.connect(new InetSocketAddress(cimServerHost, cimServerPort)).getChannel(); //这里的IP和端口根据自己情况修改 channel = bootstrap.connect(new InetSocketAddress(cimServerHost, cimServerPort)).getChannel(); //这里的IP和端口根据自己情况修改
} catch (Exception e) { } catch (Exception e) {
Intent intent = new Intent(); Intent intent = new Intent();
intent.setAction(ACTION_CONNECTION_FAILED); intent.setAction(ACTION_CONNECTION_FAILED);
intent.putExtra("exception", e); intent.putExtra("exception", e);
context.sendBroadcast(intent); context.sendBroadcast(intent);
System.out.println("******************CIM连接服务器失败 "+cimServerHost+":"+cimServerPort); System.out.println("******************CIM连接服务器失败 "+cimServerHost+":"+cimServerPort);
} }
} }
public void connect(final String cimServerHost, final int cimServerPort) { public void connect(final String cimServerHost, final int cimServerPort) {
if (!netWorkAvailable(context)) { if (!netWorkAvailable(context)) {
Intent intent = new Intent(); Intent intent = new Intent();
intent.setAction(ACTION_CONNECTION_FAILED); intent.setAction(ACTION_CONNECTION_FAILED);
intent.putExtra("exception", new NetWorkDisableException()); intent.putExtra("exception", new NetWorkDisableException());
context.sendBroadcast(intent); context.sendBroadcast(intent);
return; return;
} }
executor.execute(new Runnable() { Future<?> future = executor.submit(new Runnable() {
@Override @Override
public void run() { public void run() {
syncConnection(cimServerHost, cimServerPort); syncConnection(cimServerHost, cimServerPort);
} }
}); });
} try {
if(future.get()!=null)
public void send(final SentBody body) { {
connect(cimServerHost,cimServerPort);
}
executor.execute(new Runnable() { } catch (Exception e) {
@Override
public void run() { connect(cimServerHost,cimServerPort);
e.printStackTrace();
android.os.Message msg = new android.os.Message(); }
msg.getData().putSerializable("body", body); }
if(channel!=null && channel.isConnected()) public void send(final SentBody body) {
{
boolean isDone = channel.write(body).awaitUninterruptibly(5000);
if (!isDone) { executor.execute(new Runnable() {
@Override
Intent intent = new Intent(); public void run() {
intent.setAction(ACTION_SENT_FAILED);
intent.putExtra("exception", new WriteToClosedSessionException()); android.os.Message msg = new android.os.Message();
intent.putExtra("sentBody", body); msg.getData().putSerializable("body", body);
context.sendBroadcast(intent);
} if(channel!=null && channel.isConnected())
}else {
{ boolean isDone = channel.write(body).awaitUninterruptibly(5000);
if (!isDone) {
Intent intent = new Intent();
intent.setAction(ACTION_SENT_FAILED); Intent intent = new Intent();
intent.putExtra("exception", new CIMSessionDisableException()); intent.setAction(ACTION_SENT_FAILED);
intent.putExtra("sentBody", body); intent.putExtra("exception", new WriteToClosedSessionException());
context.sendBroadcast(intent); intent.putExtra("sentBody", body);
} context.sendBroadcast(intent);
} }
}); }else
} {
public void destroy() { Intent intent = new Intent();
if (manager.channel != null) { intent.setAction(ACTION_SENT_FAILED);
manager.channel.close(); intent.putExtra("exception", new CIMSessionDisableException());
} intent.putExtra("sentBody", body);
bootstrap.shutdown(); context.sendBroadcast(intent);
bootstrap.releaseExternalResources(); }
manager = null; }
} });
}
public boolean isConnected() {
if (channel == null) { public void destroy() {
return false; if (manager.channel != null) {
} manager.channel.close();
return channel.isConnected() ; }
} bootstrap.shutdown();
bootstrap.releaseExternalResources();
public void deliverIsConnected() { manager = null;
Intent intent = new Intent(); }
intent.setAction(ACTION_CONNECTION_FAILED);
intent.putExtra(CIMPushManager.KEY_CIM_CONNECTION_STATUS, isConnected()); public boolean isConnected() {
context.sendBroadcast(intent); if (channel == null) {
} return false;
}
return channel.isConnected() ;
}
public void closeSession()
{ public void deliverIsConnected() {
if(channel!=null) Intent intent = new Intent();
{ intent.setAction(ACTION_CONNECTION_FAILED);
channel.close(); intent.putExtra(CIMPushManager.KEY_CIM_CONNECTION_STATUS, isConnected());
} context.sendBroadcast(intent);
} }
SimpleChannelUpstreamHandler channelUpstreamHandler = new SimpleChannelUpstreamHandler() {
public void closeSession()
@Override {
public void channelConnected( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { if(channel!=null)
{
System.out.println("******************CIM连接服务器成功:"+ctx.getChannel().getLocalAddress()); channel.close();
}
Intent intent = new Intent(); }
intent.setAction(ACTION_CONNECTION_SUCCESS);
context.sendBroadcast(intent);
SimpleChannelUpstreamHandler channelUpstreamHandler = new SimpleChannelUpstreamHandler() {
}
@Override
public void channelConnected( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent event) throws Exception { System.out.println("******************CIM连接服务器成功:"+ctx.getChannel().getLocalAddress());
System.out.println("******************CIM与服务器断开连接:"+ctx.getChannel().getLocalAddress()); Intent intent = new Intent();
if(channel.getId()==ctx.getChannel().getId()) intent.setAction(ACTION_CONNECTION_SUCCESS);
{ context.sendBroadcast(intent);
Intent intent = new Intent();
intent.setAction(ACTION_CONNECTION_CLOSED); }
context.sendBroadcast(intent);
} @Override
} public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent event) throws Exception {
System.out.println("******************CIM与服务器断开连接:"+ctx.getChannel().getLocalAddress());
if(channel.getId()==ctx.getChannel().getId())
@Override {
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) Intent intent = new Intent();
throws Exception { intent.setAction(ACTION_CONNECTION_CLOSED);
context.sendBroadcast(intent);
Intent intent = new Intent();
intent.setAction(ACTION_UNCAUGHT_EXCEPTION); }
intent.putExtra("exception", e.getCause()); }
context.sendBroadcast(intent);
}
@Override @Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception { throws Exception {
if (event.getMessage() instanceof Message) { Intent intent = new Intent();
intent.setAction(ACTION_UNCAUGHT_EXCEPTION);
Intent intent = new Intent(); intent.putExtra("exception", e.getCause());
intent.setAction(ACTION_MESSAGE_RECEIVED); context.sendBroadcast(intent);
intent.putExtra("message", (Message) event.getMessage()); }
context.sendBroadcast(intent);
@Override
} public void messageReceived(ChannelHandlerContext ctx, MessageEvent event)
if (event.getMessage() instanceof ReplyBody) { throws Exception {
if (event.getMessage() instanceof Message) {
Intent intent = new Intent();
intent.setAction(ACTION_REPLY_RECEIVED); Intent intent = new Intent();
intent.putExtra("replyBody", (ReplyBody) event.getMessage()); intent.setAction(ACTION_MESSAGE_RECEIVED);
context.sendBroadcast(intent); intent.putExtra("message", (Message) event.getMessage());
} context.sendBroadcast(intent);
}
}
@Override if (event.getMessage() instanceof ReplyBody) {
public void writeComplete(ChannelHandlerContext ctx, WriteCompletionEvent event)
throws Exception {
Intent intent = new Intent();
Intent intent = new Intent(); intent.setAction(ACTION_REPLY_RECEIVED);
intent.setAction(ACTION_SENT_SUCCESS); intent.putExtra("replyBody", (ReplyBody) event.getMessage());
//intent.putExtra("sentBody", null); context.sendBroadcast(intent);
context.sendBroadcast(intent); }
}
} @Override
}; public void writeComplete(ChannelHandlerContext ctx, WriteCompletionEvent event)
throws Exception {
public static boolean netWorkAvailable(Context context) {
try { Intent intent = new Intent();
ConnectivityManager nw = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); intent.setAction(ACTION_SENT_SUCCESS);
NetworkInfo networkInfo = nw.getActiveNetworkInfo(); //intent.putExtra("sentBody", null);
return networkInfo != null; context.sendBroadcast(intent);
} catch (Exception e) {}
return false; }
} };
public static boolean netWorkAvailable(Context context) {
try {
ConnectivityManager nw = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = nw.getActiveNetworkInfo();
return networkInfo != null;
} catch (Exception e) {}
return false;
}
} }