-
Notifications
You must be signed in to change notification settings - Fork 0
/
p2p.js
286 lines (250 loc) · 8.85 KB
/
p2p.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
"use strict";
/* jshint -W097, -W099 */
/*
* @author Erno Kuusela
*/
/* global window, THREE, console, Player */
function P2P() {
// Pointer to global
this.sceneCtrl = sceneCtrl;
this.peerJsApiKey = "gnyz9wskc2chaor";
this.peerConnections = []; // used only in this file
this.netRole = null; // used all over
this.clientUpdateCallback = null; // used only in this file
this.clientKeysPressed = null; // used from pong.js
this.ThisPeerID = null; // used only in this file
this.clientID = null; // used from pong.js
this.serverID = null; // used from playerArea.js
this.timeOutTable = [];
this.clientTouch = null;
this.timeoutByServer = 7; // in seconds
this.timeoutByClient = 30000; // in milliseconds
this.playerArray = [];
this.timeoutDebug = false; // first connection will fake-timeout to exercise code
}
P2P.prototype.getPeerIdFromURL = function() {
if (window.location.search) {
var params = window.location.search.substring(1).split('&');
for (var i = 0; i < params.length; ++i) {
if (params[i].match('^peer-id')) {
return params[i].split('=')[1];
}
}
}
return null;
};
P2P.prototype.gotConnection = function(conn) {
if (conn !== undefined) {
conn.scope = this;
}
if (this.peerConnections.length > 0 && this.netRole === 'client') {
console.log("Can't handle several connections in client mode");
conn.close();
return;
}
this.peerConnections.push(conn);
this.timeOutTable.push(0);
conn.on('data', function(data) {
this.scope.gotData(conn, data);
});
if (this.netRole === 'server') {
// Add player
var randomColor = this.sceneCtrl.getRandomColor();
var newPeerID = this.peerConnections[this.peerConnections.length - 1].peer;
this.playerArray.push(new Player(newPeerID, newPeerID, randomColor));
console.log("new player, id:" + newPeerID);
this.refreshScene();
}
};
P2P.prototype.refreshScene = function() {
// Updated scene
this.sceneCtrl.playerAmount = this.playerArray.length;
this.sceneCtrl.ball.speed = this.sceneCtrl.playerAmount * 70;
this.sceneCtrl.generateScene();
};
P2P.prototype.Vec3FromArray = function(a) {
var v3 = new THREE.Vector3();
v3.copy(a);
return v3;
};
P2P.prototype.gotData = function(conn, data) {
var msg;
try {
msg = JSON.parse(data);
} catch (err) {
console.log("not JSON: " + data);
return;
}
if (this.netRole === 'client' && msg.ballpos !== undefined) {
msg.ballpos = this.Vec3FromArray(msg.ballpos);
var scope = this;
msg.racketspos = msg.racketspos.map(function(arr) {
return scope.Vec3FromArray(arr);
});
if (this.clientUpdateCallback) {
var keys = this.clientUpdateCallback(msg).keyboard;
var newSwipe = this.clientUpdateCallback(msg).touch;
var peerID = this.ThisPeerID;
conn.send(JSON.stringify({
pressedkeys: keys,
swipe: newSwipe,
playerID: peerID,
}));
} else {
console.log("update msg without handler, in " + this.netRole + " mod");
}
} else if (this.netRole === 'server' && msg.pressedkeys !== undefined) {
this.clientKeysPressed = msg.pressedkeys;
this.clientTouch = msg.swipe;
this.clientID = msg.playerID;
} else if (this.netRole === 'server') {
console.log("undefined keys in net msg");
}
// Sync scene variables
if (msg.playeramount !== undefined)
this.sceneCtrl.playerAmount = msg.playeramount;
if (msg.players !== undefined)
this.playerArray = msg.players;
};
P2P.prototype.removePeerConnection = function(conn) {
for (var i = 0; i < this.peerConnections.length; i++) {
if (conn === this.peerConnections[i]) {
this.peerConnections.splice(i, 1);
this.timeOutTable.splice(i, 1);
}
}
};
P2P.prototype.makePeer = function() {
return new Peer({
key: this.peerJsApiKey
});
};
P2P.prototype.initNet = function(updateCallback) {
var peerid = this.getPeerIdFromURL();
if (peerid !== null) {
this.initClient(updateCallback, peerid);
} else {
this.initServer();
}
};
var connectionRetries = 0;
P2P.prototype.attemptServerConnection = function(peerid) {
if ((typeof peerid) !== "string")
throw ("peerid must be string! got this: " + peerid);
var pjs = this.makePeer();
pjs.scope = this;
pjs.on('open', function(myid) {
this.scope.ThisPeerID = myid;
});
var conn = pjs.connect(peerid);
conn.on("open", function() {
console.log("connection estabilished to server");
showHelp();
});
conn.on("error", function() {
console.log("connection error to server");
});
this.gotConnection(conn);
console.log("connecting to peer " + peerid);
var connectionTimeout = function() {
var connectionOk;
var connectionFailureFaked;
if (this.timeoutDebug && conn.open === true && connectionRetries === 0) {
// fake timeout on first attempt
connectionOk = false;
connectionFailureFaked = true;
} else {
connectionOk = conn.open;
connectionFailureFaked = false;
}
if (connectionOk === false && this.netRole !== null) {
this.removePeerConnection(conn);
conn.close();
pjs.disconnect();
console.log("server connection timed out - faked=" + connectionFailureFaked);
if (connectionRetries++ < 10) {
console.log("retrying connetion, attempt #" + connectionRetries);
this.attemptServerConnection(peerid);
} else {
console.log("giving up");
// can put callback here for connection failure?
}
}
};
window.setTimeout(connectionTimeout, this.timeoutByClient /*ms*/ );
return conn;
};
P2P.prototype.initClient = function(updateCallback, peerid) {
// var conn = this.attemptServerConnection(peerid);
this.attemptServerConnection(peerid);
this.netRole = 'client';
this.clientUpdateCallback = updateCallback;
// console.log("client update callback registered");
};
P2P.prototype.initServer = function() {
this.netRole = 'server';
var pjs = this.makePeer();
var sceneCtrlPointer = this.sceneCtrl;
pjs.scope = this;
pjs.on('open', function(myid) {
this.scope.ThisPeerID = myid;
});
pjs.on('open', function(myid) {
var gamemsg = window.location.href + '?peer-id=' + myid;
// alert(gamemsg);
$("#playerUrl").html(gamemsg);
$("#urlBox").dialog("open");
if (this.scope.netRole === 'server') {
// server is always the player 0
var randomColor = sceneCtrlPointer.getRandomColor();
this.scope.playerArray[0] = new Player(myid, "server", randomColor);
sceneCtrlPointer.playerAmount = 1;
this.scope.serverID = myid;
console.log("server id:" + myid);
}
console.log(gamemsg);
showHelp();
});
pjs.on('connection', function(conn) {
this.scope.gotConnection(conn);
});
};
P2P.prototype.serverNetUpdate = function(racketPositions, ballPos, timedelta, amountPlayers) {
if (this.netRole === 'server') {
// console.log("server net update");
var update_msg = {
dt: timedelta,
racketspos: racketPositions,
ballpos: ballPos,
playeramount: amountPlayers,
players: this.playerArray,
};
var json_msg = JSON.stringify(update_msg);
for (var i = 0; i < this.peerConnections.length; i++)
if (this.peerConnections[i].open === false) {
this.timeOutTable[i] += timedelta;
if (this.timeOutTable[i] >= this.timeoutByServer) {
// peer disconnected
console.log("peer disconnected");
this.peerConnections.splice(i, 1);
this.timeOutTable.splice(i, 1);
this.playerArray.splice(i + 1, 1);
this.refreshScene();
}
} else {
if (this.timeOutTable[i] !== 0) {
this.timeOutTable[i] = 0;
}
var conn = this.peerConnections[i];
try {
conn.send(json_msg);
} catch (err) {
console.log("Send to peer connection " + i + " failed: " + err + " - removing that connection");
this.removePeerConnection(conn);
try {
conn.close();
} catch (e) {}
}
}
}
};