-
Notifications
You must be signed in to change notification settings - Fork 0
/
house_server_v1.js
118 lines (84 loc) · 2.09 KB
/
house_server_v1.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
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
//SET_UP
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var port = process.env.PORT || 7000;
app.get('*', function(req, res){
res.sendFile(__dirname + req.url);
});
server.listen(port);
console.log('Server started on port ' + port);
// Websocket
var maskPlayer = [];
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer( {'server': server} );
var allSockets = []; //for all sockets/clients
var clientIds = [];
var thisId = 0;
var maskIndex = {};
maskIndex.type = "index";
var mySocket = undefined;
//
wss.on('connection', function(ws){
mySocket = ws;
thisId++;
// clientIds.push(thisId);
ws.id = thisId;
allSockets.push(ws);
console.log('new player #%d connected!', thisId);
if(mySocket){
maskIndex.index = thisId;
mySocket.send( JSON.stringify(maskIndex) );
}
ws.on('message', function(data){
var msg = JSON.parse(data);
socketHandlers(ws, msg);
});
ws.on('close', function(){
for(var i=0; i<allSockets.length; i++){
if(allSockets[i]==ws){
var msg = {
'type': 'removePlayer',
'removeID': ws.id
};
console.log( 'Player #%d disconnected.', ws.id );
allSockets.splice(i,1);
maskPlayer.splice(i,1);
socketHandlers(ws, msg);
break;
}
}
mySocket = undefined;
});
});
var socketHandlers = function(socket,msg){
// console.log("entered socketHandlers");
//GENERAL_SENDING_DATA
for(var i=0; i<allSockets.length; i++){
try{
// ADD_ID_INFO
// msg.myID = socket.id;
if(msg.type=='addNewPlayer'){
//GENERATE_ALL_MASKPLAYERS_ONLY_ONCE
if(msg.camID==0){
msg.npID = 100;
msg.id = socket.id; // save id
msg.camID++;
console.log('NewPlayerID --> ' + msg.id);
maskPlayer.push(msg);
}
}
// SERVER_SEND_GENERAL_THING
allSockets[i].send(JSON.stringify(msg));
// SERVER_SEND_BROADCAST_THING
if(msg.type=='addNewPlayer'){
allSockets[i].send(JSON.stringify(maskPlayer));
// console.log(maskPlayer.length);
}
}
catch(error){
console.log('error of socketHandlers: ' + error);
}
}
};