socket.io Android 使用

话不多说,直接上代码
首先在项目build.gradle中添加以下代码

compile('io.socket:socket.io-client:0.8.3') {
        // excluding org.json which is provided by Android
        exclude group: 'org.json', module: 'json'
    }
  • 第一步,在Application 中配置全局socket
 private Socket mSocket;

    {
        try {
            //1.初始化socket.io,设置链接
            IO.Options opts = new IO.Options(); 
           //如果服务端使用的是https 加以下两句代码,文章尾部提供SSLSocket类
            opts.sslContext = SSLSocket.genSSLSocketFactory();
            opts.hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
            mSocket = IO.socket(Constant.SOCKET_IP, opts);
        } catch (Exception e) {
        }
    }
  • 第二步和服务器建立连接

在onCreate 建立连接

 mSocket.connect();

向外部提供一个获得socket的方法

public Socket getSocket() {
        return mSocket;
    }
  • 第三步在BaseActivity中初始化,方便子类使用
public void onCreate(@Nullable Bundle paramBundle) {
        super.onCreate(paramBundle);
        this.mPresenter = createPresenter(mPresenter);
        loading = DialogUtil.getNewLoadingDialog(mFragAct);
        app = MyApplication.getInstance();
        spUtil = app.getmSpUtil();
        mSocket = app.getSocket();
    }
  • 第四步在需要socket的地方监听服务发送的数据或向服务器发送数据
    message为监听事件名
 mSocket.on("message" , messageListener);//监听服务端发送的数据
 mSocket.emit("message", "你好");//向服务端发送数据

messageListener 接受服务器发送的数据

private Emitter.Listener messageListener = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            //主线程调用
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    JSONObject data = (JSONObject) args[0];
                    //根据个人业务处理
                    }
                }
            });
        }
    };

SSLSocket,添加支持https

public class SSLSocket {
    public static SSLContext genSSLSocketFactory() {
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    X509Certificate[] x509Certificates = new X509Certificate[0];
                    return x509Certificates;
                }
            }}, new SecureRandom());
            return sc;
        } catch (Exception localException) {
//            LogHelper.e("SSLSocketFactory -> " + localException.getMessage());
        }
        return null;
    }
}

你可能感兴趣的:(socket.io Android 使用)