我使用 socketIO 创建聊天室和命名空间。 它工作得很好,但有时我会遇到日志错误,我不知道为什么......也许当输入/输出太多时?
TypeError: Cannot read property 'room' of undefined at Socket.socket.on (/appli/chatvideodiff/server/server.js:107:48)
请看下面我的代码:
var fs = require('fs');
const cmd = require('child_process');
const express = require('express');
const path = require('path');
const http = require('http');
const https = require('https');
const socketIO = require('socket.io');
const url = require('url');
var {Message} = require('./utils/message');
const {isRealString} = require('./utils/validation');
const {Users} = require('./utils/users');
const dotenv = require('dotenv');
dotenv.config();
var options = {
key: fs.readFileSync(process.env.KEY),
cert: fs.readFileSync(process.env.CERT),
ca: fs.readFileSync(process.env.CA),
index: false,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now());
},
};
const port = process.env.PORT || 3000;
const publicPath = path.join(__dirname, '../public');
var app = express();
var server = http.createServer(options, app);
var io = socketIO(server);
var users = new Users();
var messages = new Message;
var viewersCount = [];
app.use(express.static('../public', options));
app.get('/chat/:room', function (req, res) {
var room = req.params.room;
var fqdn = req.headers.host;
var proto = process.env.PROTO;
var lien = proto + '://' + fqdn+'/index.html?room=' + room;
res.redirect(lien);
});
const io_chat = io.of("/chat").on('connection', (socket) => {
console.log("New user connected on chat from "+socket.handshake.headers['x-forwarded-for']);
socket.on('join', (params, callback) => {
if (!isRealString(params.name) || !isRealString(params.room)) {
var destination = '/urlincorrecte';
socket.emit('redirect', destination);
return false;
}
socket.join(params.room);
users.removeUser(socket.id);
users.addUser(socket.id, params.name, params.room, socket.handshake.headers['x-forwarded-for'] || socket.handshake.address.address);
io_chat.to(params.room).emit('updateUserList', users.getUserList(params.room));
var user = users.getUser(socket.id);
var msgJoin = messages.getMessageList(user.room); <== issue on this line
if (user !== undefined) {
socket.emit('history', msgJoin);
} else {
}
callback();
});
...
错误行是这一行(接近尾声):var msgJoin = messages.getMessageList(user.room);
如果你有想法,谢谢 妮可