-
Notifications
You must be signed in to change notification settings - Fork 0
/
websockets.js
58 lines (50 loc) · 1.54 KB
/
websockets.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
const ws = require('ws');
var clients = [];
var conn = null;
var peerSide = null;
var IamReady, peerReady = false;
exports.socketConnection = function(server, otherPeer) {
console.log("Connected with other Peer.. Woohooo!");
const wss = new ws.Server({ server });
conn = otherPeer.conn;
peerSide = otherPeer.side;
wss.on('connection', (socket, req) => {
handleClient(socket, req)
socket.on('message', message => {messageToPeer(message)} );
});
conn.on('data', data => {messageToClient(data)} );
}
function handleClient(socket, req) {
let ip = req.connection.remoteAddress.slice(7)
if(clients.length < 1) acceptClient(socket, ip)
else rejectClient(socket, ip)
}
function acceptClient(socket, ip){
clients.push( {"socket" : socket, "ip" : ip} )
IamReady = true;
conn.write(JSON.stringify({"type" : "ready"}))
socket.send(JSON.stringify({"type": "success"}));
if(IamReady && peerReady) startGame()
}
function rejectClient(socket, ip){
console.log(ip + " rejected");
socket.send(JSON.stringify({"type" : "fail"}));
}
function startGame(){
console.log("Game started");
clients[0]["socket"].send(JSON.stringify({"type" : "startGame", "pos" : peerSide}))
}
function messageToPeer(message){
conn.write(message)
}
function messageToClient(message){
try {
if(!peerReady && JSON.parse(message).type === "ready"){
peerReady = true;
if(IamReady && peerReady) startGame()
}
else clients[0]["socket"].send(message.toString())
} catch (e) {
console.log("Facing some troubles in websocket module :')");
}
}