-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsocket.js
46 lines (45 loc) · 1.91 KB
/
socket.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
module.exports = (io)=>{
var players = {};
let intervalId = setInterval(()=>{
io.emit('update-players',players);
},100);
io.on('connection', function(socket){
socket.ip = socket.handshake.headers['x-forwarded-for'];
//Uncomment second part below if storing to Firebase
socket.ip = socket.ip.split(',')[0]//.replace(/\./g, "_");
console.log(`New member has connected with socket id: ${socket.id} and ip: ${socket.ip}`);
socket.on('new-player',function(shared_state_data){
console.log('sending players already here');
console.log(players);
socket.emit('players-already-here',players);
console.log("New player has state:",shared_state_data);
// Add the new player to the object
players[socket.id] = shared_state_data;
let id = socket.id;
io.emit('new-player',{"id":id, "data":shared_state_data});
})
socket.on('disconnect',function(){
// Delete from object on disconnect
console.log(`Player disconnected. Removing ${socket.id}`);
delete players[socket.id];
socket.broadcast.emit('remove-player',socket.id);
})
// Online players' shared data throughput
socket.on('send-update',function(data){
if(players[socket.id] == null) return;
players[socket.id].position = data.position;
players[socket.id].rotation = data.rotation;
players[socket.id].faceIndex = data.faceIndex;
//console.log(data);
})
socket.on('msg',function(data){
if(data.key == process.env.MESSAGE_KEY){
socket.broadcast.emit('msg',{id:socket.id,msg:data.msg});
}
});
socket.on('arg',function(data){
socket.ipLocal = data;
console.log(`Client Info:\nPublic IP: ${socket.ip} Local IP: ${socket.ipLocal}`);
});
})
}