我正在尝试使用 socketio websocket 将简单数据发送到 socketio 服务器。服务器工作正常。问题:所有回调都没有做任何事情。如果连接失败,其中一个回调应该在控制台中给我写一条消息。
已授予 Internet 权限。
这是我使用的依赖项:
compile ('io.socket:socket.io-client:2.0.1') {
// excluding org.json which is provided by Android
exclude group: 'org.json', module: 'json'
}
我的代码:
import android.util.Log;
import org.json.JSONObject;
import java.net.URI;
import io.socket.client.Ack;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
import io.socket.engineio.client.transports.WebSocket;
public class MySocket {
URI uri = URI.create("https://xxxx/socket.io");
IO.Options options = IO.Options.builder()
.setTransports(new String[]{WebSocket.NAME})
.setUpgrade(true)
.setRememberUpgrade(false)
.setPath("/")
.build();
Socket socket;
public MySocket() {
socket = IO.socket(uri, options);
socket.on("hello", new Emitter.Listener() {
@Override
public void call(Object... args) {
System.out.println(args[0]); // world
}
});
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.d("ConenctioState", socket.connected()+"");
}
});
socket.on("data", new Emitter.Listener() {
@Override
public void call(Object... args) {
// ...
}
});
socket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
@Override
public void call(Object... args) {
// options.auth.put("authorization", "bearer 1234");
Log.d("Connectionerror", "call: ");
socket.connect();
}
});
socket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.d("Conenction", "call: Connection Dissconnected"); // null
}
});
}
public void sendData() {
socket.emit("test", "data", new Ack() {
@Override
public void call(Object... args) {
JSONObject response = (JSONObject) args[0];
Log.d("ack", response.toString());
}
});
}
}