1. 程式人生 > >Native Socket.IO and Android ( socket請求,與伺服器的互動)

Native Socket.IO and Android ( socket請求,與伺服器的互動)

使用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/