我无法在android中保持套接字连接。
我在我的应用程序中使用Socket.IO-client java库。
屏幕打开时,保护套接字连接。
但是,如果屏幕关闭,则ping超时会导致套接字断开连接。
我该如何解决这个问题?
我打开这样的连接。
private static final String EVENT_CONNECT = Socket.EVENT_CONNECT;
private static final String EVENT_MESSAGE = Socket.EVENT_MESSAGE;
private static final String EVENT_DISCONNECT = Socket.EVENT_DISCONNECT;
private static final String EVENT_PING = Socket.EVENT_PING;
private static final String EVENT_CONNECT_TIMEOUT = Socket.EVENT_CONNECT_TIMEOUT;
private static final String EVENT_ERROR = Socket.EVENT_ERROR;
public void connect() {
if (socket != null && socket.connected() == true) {
return;
}
IO.Options options = new IO.Options();
options.timeout = 60 * 1000;
options.reconnection = true;
Log.d(TAG, "try socket connect");
socket.on(EVENT_CONNECT, this::onConnected)
.on(EVENT_MESSAGE, this::onMessage)
.on(EVENT_DISCONNECT, this::onDisconnected)
.on(EVENT_PING, this::onPing)
.on(EVENT_CONNECT_TIMEOUT, this::onConnectTimeout)
.on(EVENT_ERROR, this::onError);
socket.connect();
}
这是我的服务器端代码
var Socket = require('socket.io');
var io = Socket(server, { 'pingInterval': 25 * 1000 });
var port = process.env.PORT || 3000;
io.on('connection', function(socket){
console.log('a user connected');
...
socket.on('disconnect', function(data){
(typeof socket.member != 'undefined') && disconnect(socket);
console.log(data);
});
});
ping间隔为25秒,超时为60秒。
当Android屏幕关闭时,客户端不适用于EVENT_PING
。另一个事件正常工作。
和服务器与日志断开连接(ping超时)。
答案 0 :(得分:4)
我解决了这个问题如下:
private static final String EVENT_PING = "ping1";
private static final String EVENT_PONG = "pong1";
public void connect() {
if (socket != null && socket.connected() == true) {
return;
}
IO.Options options = new IO.Options();
options.timeout = 60 * 1000;
options.reconnection = true;
Log.d(TAG, "try socket connect");
socket.on(EVENT_CONNECT, this::onConnected)
.on(EVENT_MESSAGE, this::onMessage)
.on(EVENT_DISCONNECT, this::onDisconnected)
.on(EVENT_PING, this::onPing)
.on(EVENT_CONNECT_TIMEOUT, this::onConnectTimeout)
.on(EVENT_ERROR, this::onError);
socket.connect();
}
private void onPing(Object... args) {
Log.d(TAG, "socket ping");
socket.emit(EVENT_PONG);
}
这是服务器代码。
var pingInterval = 25 * 1000;
var Socket = require('socket.io');
var io = Socket(server, { 'pingInterval': pingInterval });
var port = process.env.PORT || 3000;
io.on('connection', function(socket){
console.log('a user connected');
function sendPing() {
socket.emit('ping1');
}
setTimeout(sendPing, pingInterval);
socket.on('disconnect', function(data){
(typeof socket.member != 'undefined') && disconnect(socket);
console.log(data);
});
socket.on('pong1', function(data) {
setTimeout(sendPing, pingInterval);
console.log('pong');
});
});