-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
71 lines (57 loc) · 1.43 KB
/
server.js
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
// server for collaborative pad
var http = require('http'),
io = require('socket.io'); // for npm, otherwise use require('./path/to/socket.io')
var clients = [];
server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Hello world</h1>');
});
server.listen(8080);
var full_text = '';
// socket.io
var socket = io.listen(server);
socket.on('connection', function(client){
var your_id = new Date().getTime();
var client_data = {
'client_id': your_id,
'client': client
};
clients.push(client_data);
//console.log(clients);
client.on('connect', function(){
//console.log(client_data);
console.log('client connected');
});
client.on('message', function(recv_message){
if(recv_message.opcode == 'diff')
{
console.log('diff received');
send_to_peers(recv_message);
full_text = recv_message.full_text;
}
else if(recv_message.opcode == 'connect')
{
client.send({'opcode': 'connected', 'full_text': full_text});
}
});
function send_to_peers(message_to_send)
{
for(var i = 0; i < clients.length; i++)
{
if(clients[i]['client_id'] != your_id)
{
clients[i]['client'].send(message_to_send);
}
}
}
function send_to_all(message_to_send)
{
for(var i = 0; i < clients.length; i++)
{
clients[i]['client'].send(message_to_send);
}
}
client.on('disconnect', function(){
console.log("Disconnected");
});
});