forked from tconn89/BezierCurves
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
78 lines (64 loc) · 2.06 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
72
73
74
75
76
77
78
// content of index.js
const http = require('http')
const WebSocketServer = require('websocket').server;
const port = 8080
app = require('./app')
app.set('port', port);
const server = http.createServer(app)
var spectators = [];
var clients = [];
server.listen(port, 'localhost', (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', function(request) {
var connection = request.accept(null, request.origin);
// This is the most important callback for us, we'll handle
// all messages from users here.
connection.on('message', function(message) {
if (message.type === 'utf8') {
// console.log(message.utf8Data);
// connection.sendUTF(JSON.stringify({ data: 'shutup client'} ))
var obj = JSON.parse(message.utf8Data);
if(obj.type == 'spectator'){
console.log('new spectator joined')
spectators.push({connection: connection, id: obj.id})
clients.forEach(function(client){
client.connection.sendUTF(JSON.stringify({id: obj.id, type: 'specAdded'}))
})
return;
}
if(obj.type == 'bezier'){
clients.push({connection: connection, id: obj.id });
}
if(obj.type == 'specLeft'){
console.log('Spectator Left');
return;
}
if(obj.curve){
spectators.forEach(function(spectator){
spectator.connection.sendUTF(JSON.stringify(obj));
})
}
else {
// console.log('message type: ' + obj.type)
// console.log('message id: ' + obj.id)
console.log('message data: ' + obj.data)
}
// back to spectator client
// find all spectator clients and send them curve data based on id
// connection.sendUTF(JSON.stringify(obj));
} else if(message.type == 'CloseEvent')
console.log('Spectator Left')
});
connection.on('close', function() {
// close user connection
//console.log(connection.id)
});
});
// changes