我正在从node.js服务器向android客户端发送一个echo请求,Android客户端需要50ms到150ms来接收消息。当我从android客户端向服务器发起一个echo请求时,我可以得到一个往返发射和ack在6ms以下一致。使用chrome on chrome浏览器的相同设置在3ms内响应服务器。这个库中是否有一些配置设置可以减少发送到Android客户端的消息的延迟,或者这是继承到Android设备上的协议的东西?我尝试过运行4.4.4和5.1.1的两个不同的Android设备。以下是在我的android活动中运行的代码。
mSocket = IO.socket(Routes.SocketController);
} catch (URISyntaxException e) {
Log.d(TAG, e.toString());
}
mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.d(TAG, "event connect");
}
});
mSocket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.d(TAG, "event disconnect");
}
});
// respond to request from server with client current time
mSocket.on(Const.Ping,new Emitter.Listener() {
@Override
public void call(Object... args) {
Date now = new Date();
mSocket.emit(Const.Pong, now.getTime());
}
});
我正在使用node.js v5.4.1 socket.io.client-java 0.6.3 Nexus 4上的Android 5.1.1
使用koush AndroidAsync库再次尝试并且性能仍然不佳
public class AndroidAsyncWebSockets {
private static final String TAG = AndroidAsyncWebSockets.class.getSimpleName();
private WebSocket mSocket;
public AndroidAsyncWebSockets() {
Log.d(TAG, "AndroidAsync object created");
connectWebSocket();
}
private void connectWebSocket() {
URI uri;
Routes routes = new Routes("test");
String server = routes.webSocketController();
try {
uri = new URI(server);
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
Log.d(TAG, "connecting to " + uri.toString());
AsyncHttpClient.WebSocketConnectCallback mWebSocketConnectCallback = new AsyncHttpClient.WebSocketConnectCallback() {
@Override
public void onCompleted(Exception ex, WebSocket webSocket) {
if (ex != null) {
ex.printStackTrace();
return;
}
mSocket = webSocket;
webSocket.setStringCallback(new WebSocket.StringCallback() {
@Override
public void onStringAvailable(String s) {
processCommand(s);
}
});
}
};
AsyncHttpClient mAsyncHttpClient = AsyncHttpClient.getDefaultInstance();
mAsyncHttpClient.websocket(uri.toASCIIString(), null, mWebSocketConnectCallback);
}
public void processCommand(String message) {
String cmd="";
String data="";
try {
JSONObject jsonObject = new JSONObject(message);
cmd = jsonObject.getString("cmd");
data = jsonObject.getString("data");
}
catch(JSONException e) {
Log.d(TAG, "onmessage " + e.toString());
}
switch (cmd) {
case "Ping" :
//Log.d(TAG, "Ping " + data);
sendPong();
break;
}
}
public void sendPong() {
Date now = new Date();
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("cmd", Const.Pong);
jsonObject.put("data", now.getTime());
sendMessage(jsonObject.toString());
}
catch (JSONException e) {
Log.d(TAG, "sendPong " + e.toString());
}
}
public void sendMessage(String text) {
mSocket.send(text);
}
}