我使用API構建了一個服務器。它使用Axios進行未記錄的呼叫,使用Socket.io進行記錄的呼叫。 然後我有一個網站連接到它。這完美地工作。 但我也有一個內置的react-native應用程序,它有一個奇怪的行爲:它打開每個發射的連接而不關閉它們以前的連接。正如你在下面看到的,我console.log websocket.engine.clientsCount在服務器上。每當我從電話應用程序發出時,它都會打開一個新的連接,找到服務器的數量不斷增加。Socket.io與React-Native打開多個連接
在服務器上,用戶我以下版本:
"connect-mongo": "^1.3.2",
"express": "^4.14.1",
"express-session": "^1.12.1",
"jwt-simple": "^0.5.1",
"mongodb": "^2.2.30",
"mongoose": "^4.11.5",
"passport": "^0.3.2",
"passport-jwt": "^2.2.1",
"passport-local": "^1.0.0",
"socket.io": "^1.7.3",
"socketio-jwt": "^4.5.0"
這裏的API的代碼。爲了清晰起見,我刪除了一些代碼
const passport = require('passport');
const express = require('express');
const session = require('express-session');
const http = require('http');
const morgan = require('morgan');
const mongoose = require('mongoose');
const socketio = require('socket.io');
const bodyParser = require('body-parser');
const socketioJwt = require("socketio-jwt"); // da commentare
const Users = require('../models/users');
const passportService = require('./services/passport');
const requireAuth = passport.authenticate('jwt', {session: false});
const requireLogin = passport.authenticate('local', {session: false});
const config = require('./config');
const app = express();
const socketRouter = require('./services/socketRouter');
const MongoStore = require('connect-mongo')(session);
const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost/blablabla';
mongoose.connect(mongoUri);
...
const server = http.Server(app);
const websocket = socketio(server);
// add authorization for jwt-passport when first connection -> https://github.com/auth0/socketio-jwt
websocket.use(socketioJwt.authorize({
secret: config.secret,
handshake: true
}));
const sessionMiddleware = session({
store: new MongoStore({ // use MongoDb to store session (re-using previous connection)
mongooseConnection: mongoose.connection,
ttl: (1 * 60 * 60)
}),
secret: config.secretSession,
httpOnly: true,
resave: false,
saveUninitialized: false,
cookie: { maxAge: 86400000 }
});
app.use(sessionMiddleware);
...
websocket.on('connection', (socket) => {
Users.findById(socket.decoded_token.sub, function(err, user) {
if (err) { console.log('the user wasn\'t find in database', err); }
if (user) {
socket.join(user._id);
console.log('Clients connected: ', websocket.engine.clientsCount);
// ------ PROTECTED EVENTS ------ //
...
// ------------------------------ //
}
socket.on('disconnect',()=> {
socket.leave(user._id);
onsole.log('user disconnected');
});
});
});
...
我不會把網站的初始化,因爲它運作良好。
在移動應用程序,我的用戶以下版本:
"react-native": "^0.41.0",
"react-native-keychain": "^1.1.0",
"socket.io-client": "^1.7.3",
"socketio-jwt": "^4.5.0"
這裏是反應本地應用程序的innitialisation。
import * as Keychain from 'react-native-keychain';
import { BASIC_WS_URL } from '../api';
const io = require('socket.io-client/dist/socket.io');
const socketEvents = require('./events');
exports = module.exports = (store) => {
Keychain.getGenericPassword().then((credentials) => {
if (credentials && credentials !== false) {
const { password } = credentials;
const websocket = io(BASIC_WS_URL, {
jsonp: false,
transports: ['websocket'], // you need to explicitly tell it to use websockets
query: {
token: password
}
});
websocket.connect();
websocket.on('connect', (socket) => {
console.log('Connected');
});
websocket.on('reconnect', (socket) => {
console.log('Re-connected');
});
websocket.on('disconnect', (socket) => {
console.log('Disconnected');
});
// all the events to listen
socketEvents(websocket, store);
}
});
};
我在做什麼錯?
根據我的理解,問題在於React-Native中的套接字是全局的。每次我發射時,它都會打開一個新的連接而不關閉前一個連接。 我正在嘗試初始化套接字並使其成爲全局的,以便能夠在動作創建器中發出。如果我使用'context',我可以在其他組件中檢索已初始化的套接字,但它不會再發出(我錯過了我猜測的圓形對象的概念)。另外,授權連接的鑰匙串標記是異步的,並且它不適用於生命週期組件功能。 有沒有人有工作實施? – Pibo