实际开发中,android 通过socket.io 连接 nodejs socket接口。特此做以下记录:
-------------------------------------------------------------------------
socket.io相关知识传送门:http://socket.io/blog/
-------------------------------------------------------------------------
android实际开发正式开始:
step1.引入socket.io
dependencies {
compile('io.socket:socket.io-client:0.7.0') {
exclude group: 'org.json', module: 'json'
}
}
step2.建立socket 连接
public class MyApplication extends Application {
private static final String TAG = "scada";
@Override
public void onCreate() {
super.onCreate();
}
private Socket mSocket;
{
try {
IO.setDefaultSSLContext(HttpsUtil.getSslContext());
IO.setDefaultHostnameVerifier(HttpsUtil.hostnameVerifier);
IO.Options options = new IO.Options();
options.path = "/socket.io";
mSocket = IO.socket(StaticWords.SOCKET_SERVER_URL, options);
mSocket.connect();
mSocket.open();
} catch (URISyntaxException e) {
Log.e(TAG, "Socket:"+e.getMessage());
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "Socket:"+e.getMessage());
throw new RuntimeException(e);
} catch (KeyManagementException e) {
Log.e(TAG, "Socket:"+e.getMessage());
throw new RuntimeException(e);
}
}
public Socket getSocket() {
return mSocket;
}
}
对于一个APP来说,全程只需要建立一个socket对象即可,所以此处选择在Application下实现socket对象的初始化和连接。
step3.socket 方法
声明对象:
private Socket mSocket;
socket 方法:
//socket 初始化
private void socketInit() {
//socket 连接
MyApplication socket = (MyApplication) getApplication();
mSocket = socket.getSocket();
//socket 接受(此处以allCount方法举例)
mSocket.on("allCount", allCount);
}
//socket 接受
private Emitter.Listener allCount = new Emitter.Listener() {
@Override
public void call(Object... args) {
//TODO 接收到socket返回值,以下接着做具体业务
}
};
<pre style="background-color: rgb(255, 255, 255); font-family: "Courier New"; font-size: 9.8pt;"><pre name="code" class="java">//socket 发送
private void socketSend() {
//请求参数
JSONObject paramObj = new JSONObject();
if (mSocket != null) {
//此代码含义:socket断开连接,再次发送时重连
mSocket.connect();
if (mSocket.connected()) {
Log.e(TAG, "allCount -- 发送 -- Socket");
mSocket.emit("allCount", paramObj);
} else {
Log.e(TAG, "mSocket 断开连接");
}
}
}
//socket 关闭接收
private void socketOff(){
if (mSocket != null) {
mSocket.off("allCount");
}
}
step4.socket 具体使用
此处以某个Activity作为应用环境作简单介绍。
① onCreate执行:socketInit();socketSend();
②Activity内实现socket接受监听
③socket监听(此处是allCount)里获取后台socket返回数据,并进行具体业务逻辑处理。
④onStop执行:socketOff();
以上,就是关于android使用socket.io开源框架实现socket连接的简单介绍,如有不足,后续再补充。