我是用的一個框架
首先依賴
compile ('io.socket:socket.io-client:1.0.0') {
// excluding org.json which is provided by Android
exclude group: 'org.json', module: 'json'
}
//主要代碼
final String wsurl="*******";
Socket socket = IO.socket(wsurl);
//2.建立socket.io服務器的連接
socket.connect();
//參數上傳
JSONObject loginData=new JSONObject();
loginData.put("room_id",roomID);
loginData.put("user_id", userID);
loginData.put("nick_name",name);
loginData.put("from", "android");
loginData.put("avatar",avatar);
//傳遞數據
socket.emit("login",loginData);
// 服務端方法調用
socket.on("login", new Emitter.Listener() {
@Override
public void call(Object... args) {
JSONObject obj = (JSONObject)args[0];
mTvWatchNum.setText("1");
}
});
//接收服務端消息數據
socket.on("message",new Emitter.Listener(){
@Override
public void call(Object... args) {
Log.i("11",args.toString());
//處理服務端消息數據
}
});
在退出頁面的時候要關閉連接
socket.disconnect();