forked from schifano/codelab
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsocket.js
More file actions
130 lines (77 loc) · 2.4 KB
/
Copy pathsocket.js
File metadata and controls
130 lines (77 loc) · 2.4 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
var io = require('socket.io').listen(8080);
var users = [];
//
// On Connect
//
io.sockets.on('connection', function (socket) {
// Emit the session_id in user object.
io.sockets.socket(socket.id).emit('session-id', {'session_id': socket.id});
// Fired when the client sends a user to update to the server.
socket.on('update-user', function (user) {
// Let's search for this user.
var found = false;
for(var i = 0; i < users.length; i++){
// If the user is in the array...
if(users[i].session_id == this.id){
found = true;
// Add the updated user.
users[i] = user;
// Tell partners of this user about the update.
updateUser(user);
}
}
// If the user is not in the array...
if(!found){
// Then we add the user to the array.
users.push(user);
// Nobody is their partner yet!
}
});
// Fired when the client requests to refresh the friends list.
// (This happens when nicknames are changed.)
socket.on('refresh-friends', function(user){
var friends = [];
var friend = {};
// Build a list of online friends.
for(var i = 0; i < users.length; i++){
friend.session_id = users[i].session_id;
friend.nickname = users[i].nickname;
friends.push(friend);
friend = {};
}
// Emit the friends list to everyone...
socket.broadcast.emit('friends-broadcast', friends);
// including the user who made the request.
socket.emit('friends-broadcast', friends);
});
//
// On Disconect
//
socket.on('disconnect', function () {
for(var i = 0; i < users.length; i++){
if(users[i].session_id == this.id){
users.splice(i,1);
}
}
// Tell everyone a friend has disconnected.
// Clients will then request an updated friends list.
socket.broadcast.emit('friend-disconnect');
});
// Fired when the client requests to see their partner's code.
socket.on('fetch-code', function(partnerID) {
for(var i = 0; i < users.length; i++) {
if(users[i].session_id == partnerID) {
socket.emit('retrieve-code', users[i].textarea);
}
}
});
// Tells partners of user about changes made to their text file.
function updateUser(userIn) {
for(var i = 0; i < users.length; i++) {
if(users[i].partner_id == userIn.session_id) {
console.log("found partner");
io.sockets.socket(users[i].session_id).emit('watch-code', userIn);
}
}
}
});