android socket.io client,java|android 使用socket.io-client连接nodejs websocket

汪才
2023-12-01

socket.io-client相比SocketIO.jar使用起来更方便一点

public void connection(final MapAction _action) {

try {

IO.Options opts = new IO.Options();

opts.query = "w_auth_key=" +LoginActivity.socket_auth_key;//传参数

Socket socket = IO.socket("ip/", opts);

socket.connect();

socket.emit("initAllShips");//请求websocket后台方法

socket.on("setInitShips", new Emitter.Listener() { //监听回调函数

@Override

public void call(Object... args) {

System.out.println("回调了参数:"+args[0]);

}

});

} catch (Exception e1) {

e1.printStackTrace();

}

}

maven

com.github.nkzawa

socket.io-client

0.5.0

socket = IO.socket("http://localhost");

socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

@Override

public void call(Object... args) {

socket.emit("foo", "hi");

socket.disconnect();

}

}).on("event", new Emitter.Listener() {

@Override

public void call(Object... args) {}

}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

@Override

public void call(Object... args) {}

});

socket.connect();

This Library uses

org.json

to parse and compose JSON strings:

// Sending an object

JSONObject obj = new JSONObject();

obj.put("hello", "server");

obj.put("binary", new byte[42]);

socket.emit("foo", obj);

// Receiving an object

socket.on("foo", new Emitter.Listener() {

@Override

public void call(Object... args) {

JSONObject obj = (JSONObject)args[0];

}

});

IO.Options opts = new IO.Options();

opts.forceNew = true;

opts.query = "auth_token=" + authToken;

Socket socket = IO.socket("http://localhost", opts);

 类似资料: