-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathsocket.js
More file actions
72 lines (69 loc) · 1.89 KB
/
socket.js
File metadata and controls
72 lines (69 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
var cookie = require('express/node_modules/cookie');
var Contest = require('./models/contest.js');
module.exports = function(io, sessionStore) {
//多进程运行需要
io.adapter(require('socket.io-redis')({
host: 'localhost',
port: 6379
}));
//socket验证cookie并获取会话
io.use(function(socket, next){
var handshakeData = socket.request;
if (!handshakeData.headers.cookie) {
return next(new Error('no cookie.'));
}
handshakeData.cookie = cookie.parse(handshakeData.headers.cookie);
var sid = handshakeData.cookie['connect.sid'];
if (!sid) {
return next(new Error('no sid.'));
}
sessionStore.get(sid.split(':')[1].split('.')[0], function(err, session){
if (err) {
return next(err);
}
if (!session) {
return next('no session.');
}
socket.session = session;
next();
});
});
//socket连接
io.on('connection', function(socket){
var session = socket.session;
if (session && session.user) {
var name = session.user.name;
//监听广播请求
socket.on('broadcast', function(data, fn){
if (data) {
var cid = parseInt(data.room, 10);
if (!cid) {
return ; //not allow
}
Contest.watch(cid)
.then(function(contest){
if (contest && (name === 'admin' || name === contest.userName)) {
socket.broadcast.to(data.room).emit('broadcast', data.msg);
if (fn) {
fn(true);
}
}
})
.done();
}
});
}
//加入比赛房间
socket.on('login', function(room){
if (room) {
socket.join(room.toString());
}
});
//discuss实时提醒
socket.on('addDiscuss', function(room){
if (room) {
socket.broadcast.to(room).emit('addDiscuss');
}
});
});
};