版本列表:
{
"react": "16.3.1",
"react-native": "0.55.4"
"socket.io-client": "^2.1.1"
}
客户端中app.js中的代码:
.....
import io from 'socket.io-client/dist/socket.io';
const server = "https://xxx.xxx.xxx.xxx/";
let socket = io(server, {
'reconnection' : true,
'reconnectionDelay' : 500,
'reconnectionAttempts': Infinity,
'transports' : ['websocket']
});
socket.on('connect', () => {
console.log("connect");
});
......
nodeJS服务器代码
....
const io = require('socket.io')(httpsServer);
....
let clients = {};
let count = 0;
io.on('connection', function (socket) {
clients[socket.id] = socket;
socket.emit("all message", 'data'); //send successfully
socket.on("disconnect",() => {
console.log("disconnect"); // Disconnect after 30 seconds
delete clients[socket.id];
})
});
setInterval(() => {
count+=Object.keys(clients).length;
console.log(count); // will stop at count value 30
},1000)
连接成功30秒后,客户端react-native中的socket.io-client将自动断开连接。