使用GitHub上开源框架实现socket
1.在build文件中引入:compile 'com.github.nkzawa:socket.io-client:0.3.0'
-- 链接 : https://github.com/nkzawa/socket.io-android-chat (英文的文档,中文的可以百度上搜一下)
2.在manifest中添加网络权限 <uses-permission android:name="android.permission.INTERNET" />
3.加入到服务器端socket
private Socket mSocket;
{
try {
mSocket = IO.socket("http://192.168.xxx.xxx:xxxx");//ip与端口与服务器一致
} catch (URISyntaxException e) {
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = x.view().inject(this, inflater, container);
initSockte();
return view;
}
4.
private void initSockte() {
mSocket.on("tic", onNewMessage);//与服务器保持一致
mSocket.connect();
}
//
private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(final Object... args) {
if(getActivity()==null){
return;
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = (JSONObject) args[0];
String jj ;
try {
jj = data.getString("close");
} catch (JSONException e) {
e.printStackTrace();
return;
}
}
});
}
};
5.关闭连接
@Override
public void onDestroyView() {
Log.i("socketlog","我关啦");
super.onDestroyView();
if(mSocket!=null){
mSocket.disconnect();
mSocket.off("tic", onNewMessage);
}
}
主要的方法在 on(),off(),还有事件监听,与服务器端事件相同。
友情链接:https://socket.io/blog/native-socket-io-and-android/