-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.socket.js
More file actions
82 lines (73 loc) · 2.13 KB
/
util.socket.js
File metadata and controls
82 lines (73 loc) · 2.13 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
73
74
75
76
77
78
79
80
81
82
const socketIo = require("socket.io");
module.exports = function (waw) {
if (!waw.server) {
throw new Error("util.socket requires waw.server (call util.express first)");
}
const io = new socketIo.Server(waw.server, {
cors: { origin: "*" },
transports: ["websocket", "polling"]
});
/*
* Sockets API (same behavior)
*/
let connections = [
function (socket) {
socket.on("create", function (content) {
socket.broadcast.emit("create", content);
});
socket.on("update", function (content) {
socket.broadcast.emit("update", content);
});
socket.on("unique", function (content) {
socket.broadcast.emit("unique", content);
});
socket.on("delete", function (content) {
socket.broadcast.emit("delete", content);
});
},
];
waw.socket = {
io: io,
emit: function (to, message, room = false) {
if (room) {
io.in(room).emit(to, message);
} else {
io.emit(to, message);
}
},
add: function (connection) {
if (typeof connection == "function") connections.push(connection);
},
};
io.on("connection", function (socket) {
for (var i = 0; i < connections.length; i++) {
if (typeof connections[i] === "function") {
connections[i](socket);
}
}
});
};
/*
waw.socket.add(function(socket){
if (socket.request.user) {
socket.join(socket.request.user._id);
}
})
/*
// sending to sender-client only
socket.emit('message', "this is a test");
// sending to all clients, include sender
io.emit('message', "this is a test");
// sending to all clients except sender
socket.broadcast.emit('message', "this is a test");
// sending to all clients in 'game' room(channel) except sender
socket.broadcast.to('game').emit('message', 'nice game');
// sending to all clients in 'game' room(channel), include sender
io.in('game').emit('message', 'cool game');
// sending to sender client, only if they are in 'game' room(channel)
socket.to('game').emit('message', 'enjoy the game');
// sending to all clients in namespace 'myNamespace', include sender
io.of('myNamespace').emit('message', 'gg');
// sending to individual socketid
socket.broadcast.to(socketid).emit('message', 'for your eyes only');
*/