-
Notifications
You must be signed in to change notification settings - Fork 0
/
house_server_vL.js
132 lines (92 loc) · 2.47 KB
/
house_server_vL.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var port = process.env.PORT || 7000;
// peer_server
var ExpressPeerServer = require('peer').ExpressPeerServer;
var peerExpress = require('express');
var peerApp = peerExpress();
var peerServer = require('http').createServer(peerApp);
var options = { debug: true };
var peerPort = 5000;
app.get('*', function(req, res){
res.sendFile(__dirname + req.url);
});
peerApp.use('/pp', ExpressPeerServer(peerServer, options));
server.listen(port);
peerServer.listen(peerPort);
console.log('Server started on port ' + port);
console.log('PeerServer started on port ' + peerPort);
// 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);
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': clientIds[i]
};
console.log( 'Player #%d disconnected.', clientIds[i] );
allSockets.splice(i,1);
clientIds.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.camID++;
console.log('NewPlayerID --> ' + msg.peerid);
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);
}
}
};