1.导入依赖
implementation (\'io.socket:socket.io-client:1.0.0\') {exclude group: \'org.json\', module: \'json\' // excluding org.json which is provided by Android}
2.实现连接
try { mSocket = IO.socket(\"http://localhost:3001\");//连接地址
mSocket.connect();实现连接
} catch (URISyntaxException e) {LogUtils.d(TAG, e.toString());e.printStackTrace();}
3.监听连接状态和消息接收
try {mSocket = IO.socket(\"http://localhost:3001\");mSocket.on(Socket.EVENT_CONNECT, args ->LogUtils.d(TAG, Socket.EVENT_CONNECT)//监听连接).on(Socket.EVENT_CONNECTING, args ->LogUtils.d(TAG, Socket.EVENT_CONNECTING)//连接中).on(Socket.EVENT_DISCONNECT, args ->LogUtils.d(TAG, Socket.EVENT_DISCONNECT)//监听断开连接).on(Socket.EVENT_CONNECT_ERROR, args ->LogUtils.d(TAG, Socket.EVENT_CONNECT_ERROR)//连接错误).on(Socket.EVENT_ERROR, args ->LogUtils.d(TAG, Socket.EVENT_ERROR)).on(\"users\", args -> {JSONObject obj = (JSONObject) args[0];try {String type = obj.getString(\"type\");Intent intent = new Intent();intent.setAction(Constant.BROADCAST_ACTION);intent.putExtra(\"type\", type);sendBroadcast(intent);//接收到消息后发送广播LogUtils.d(TAG, obj.toString());} catch (JSONException e) {e.printStackTrace();}});mSocket.connect();} catch (URISyntaxException e) {LogUtils.d(TAG, e.toString());e.printStackTrace();}
4.发送信息
// Sending an objectJSONObject obj = new JSONObject();obj.put(\"hello\", \"server\");obj.put(\"binary\", new byte[42]);socket.emit(\"foo\", obj);// Receiving an objectmSocket.on(\"users\", new Emitter.Listener() {@Overridepublic void call(Object... args) {JSONObject obj = (JSONObject)args[0];}});