我正在尝试使用socket.io房间的概念创建一个私人聊天室。当用户点击另一个用户的名字时,会开始比较,如果有一个房间同时包含两个用户,那么它将加入房间,否则将创建一个包含两个用户的新房间。 当消息到达时,消息被发送到相应的房间,但我的代码不起作用:比较完成,找到相应的ID,但是为连接到tchat的每个人发送消息。
这是服务器的代码
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var port = process.env.PORT || 8080;
var cookieParser = require('cookie-parser');
var session = require('express-session');
var morgan = require('morgan');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var passport = require('passport');
var flash = require('connect-flash');
//session-store
var MongoStore = require('connect-mongo')(session);
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
require('./config/passport')(passport);
var Room = require('./app/models/room');
var User = require('./app/models/user');
//session
var sessionMiddleware = session({
secret: 'anystringoftext',
saveUninitialized: true,
resave: true,
store: new MongoStore({
mongooseConnection: mongoose.connection
}),
ttl: 2 * 24 * 60 * 60
});
//fonction btoa
var btoa = require('btoa');
var atob = require('atob');
//session with socket.io
io.use(function(socket, next) {
sessionMiddleware(socket.request, {}, next);
});
io.on('connection', function(socket) {
socket.on('startchat', function(name) {
//my id
var idUser = socket.request.session.passport.user;
//search for my name
User.findById(idUser, function(err, user) {
if (err) throw err;
if (user) {
//my name
nameUser = user.local.username;
if (name < nameUser) {
var users = name + ',' + nameUser;
} else {
var users = nameUser + ',' + name;
}
//encrypt the string
var roomid = btoa(users);
//searching fo ra corresponding id
Room.find(function(err, room) {
if (err) throw err;
if (room) {
var dRoom = '';
room.forEach(function(room) {
var idRoom = atob(room.id).split(',');
//comparaison
if ((idRoom[0] == nameUser && idRoom[1] == name) || (idRoom[0] == name && idRoom[1] == nameUser)) {
dRoom = room.id;
console.log(idRoom, room.id);
//join the room
socket.join(dRoom);
}
});
if (dRoom == '') {
//we didn't find an id which corresponds so we create a room with this id
dRoom = roomid;
var newroom = new Room({
id: roomid
});
newroom.save();
console.log('created');
console.log(atob(roomid).split(','));
console.log(roomid);
//join the room
socket.join(roomid);
}
}
//when msg is emitted
socket.on('message', function(msg) {
console.log('message', dRoom);
//emit the msgs to this room
io.sockets.in(dRoom).emit('msg', msg);
});
});
}
});
});
app.use(express.static('public'));
app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(sessionMiddleware);
//passport and sessions
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.set('view engine', 'ejs');
require('./app/routes.js')(app, passport);
server.listen(port, function() {
console.log('Server running on port: ' + port);
});
client.js
$(document).ready(function(){
var socket = io();
socket.on('connect', function() {
// Connected, let's sign-up for to receive messages for this room
$('#chat').hide();
var start;
window.start = function (id,name){
$('#chat').show();
$('#chatHeader').html(name);
socket.emit('startchat', name);
}
$('#send').submit(function(event){
event.preventDefault(); //empeche la page de se recharger
var msg = $('#message').val();
if(msg !== ''){
socket.emit('message', msg);
}
$('#message').val('');
});
});
socket.on('msg', function(msg){
$('.messages').append('<div>'+ msg + '</div>');
});
});