peerpigeon 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1187 -0
- package/examples/browser/app-dht-disabled.js +42 -0
- package/examples/browser/app.js +51 -0
- package/examples/browser/assets/images/favicon.png +0 -0
- package/examples/browser/assets/images/pigeon.png +0 -0
- package/examples/browser/index-dht-disabled.html +123 -0
- package/examples/browser/index.html +340 -0
- package/examples/browser/styles.css +1288 -0
- package/examples/browser/ui-clean.js +0 -0
- package/examples/browser/ui.js +1930 -0
- package/index.js +8 -0
- package/package.json +70 -0
- package/server/index.js +515 -0
- package/src/CleanupManager.js +181 -0
- package/src/ConnectionManager.js +841 -0
- package/src/EventEmitter.js +27 -0
- package/src/EvictionManager.js +257 -0
- package/src/GossipManager.js +416 -0
- package/src/MediaManager.js +225 -0
- package/src/MeshOptimizer.js +181 -0
- package/src/PeerConnection.js +831 -0
- package/src/PeerDiscovery.js +297 -0
- package/src/PeerPigeonMesh.js +703 -0
- package/src/SignalingClient.js +536 -0
- package/src/SignalingHandler.js +325 -0
- package/src/StorageManager.js +88 -0
- package/src/TimerUtils.js +46 -0
- package/src/WebDHT.js +1099 -0
- package/websocket-server/README.md +257 -0
- package/websocket-server/memory-leak-test.js +193 -0
- package/websocket-server/node_modules/.package-lock.json +29 -0
- package/websocket-server/node_modules/ws/LICENSE +20 -0
- package/websocket-server/node_modules/ws/README.md +548 -0
- package/websocket-server/node_modules/ws/browser.js +8 -0
- package/websocket-server/node_modules/ws/index.js +13 -0
- package/websocket-server/node_modules/ws/lib/buffer-util.js +131 -0
- package/websocket-server/node_modules/ws/lib/constants.js +18 -0
- package/websocket-server/node_modules/ws/lib/event-target.js +292 -0
- package/websocket-server/node_modules/ws/lib/extension.js +203 -0
- package/websocket-server/node_modules/ws/lib/limiter.js +55 -0
- package/websocket-server/node_modules/ws/lib/permessage-deflate.js +528 -0
- package/websocket-server/node_modules/ws/lib/receiver.js +706 -0
- package/websocket-server/node_modules/ws/lib/sender.js +602 -0
- package/websocket-server/node_modules/ws/lib/stream.js +161 -0
- package/websocket-server/node_modules/ws/lib/subprotocol.js +62 -0
- package/websocket-server/node_modules/ws/lib/validation.js +152 -0
- package/websocket-server/node_modules/ws/lib/websocket-server.js +550 -0
- package/websocket-server/node_modules/ws/lib/websocket.js +1388 -0
- package/websocket-server/node_modules/ws/package.json +69 -0
- package/websocket-server/node_modules/ws/wrapper.mjs +8 -0
- package/websocket-server/package-lock.json +39 -0
- package/websocket-server/server.js +298 -0
- package/websocket-server/test.js +133 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "ws",
|
|
3
|
+
"version": "8.18.3",
|
|
4
|
+
"description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"HyBi",
|
|
7
|
+
"Push",
|
|
8
|
+
"RFC-6455",
|
|
9
|
+
"WebSocket",
|
|
10
|
+
"WebSockets",
|
|
11
|
+
"real-time"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://github.com/websockets/ws",
|
|
14
|
+
"bugs": "https://github.com/websockets/ws/issues",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/websockets/ws.git"
|
|
18
|
+
},
|
|
19
|
+
"author": "Einar Otto Stangvik <einaros@gmail.com> (http://2x.io)",
|
|
20
|
+
"license": "MIT",
|
|
21
|
+
"main": "index.js",
|
|
22
|
+
"exports": {
|
|
23
|
+
".": {
|
|
24
|
+
"browser": "./browser.js",
|
|
25
|
+
"import": "./wrapper.mjs",
|
|
26
|
+
"require": "./index.js"
|
|
27
|
+
},
|
|
28
|
+
"./package.json": "./package.json"
|
|
29
|
+
},
|
|
30
|
+
"browser": "browser.js",
|
|
31
|
+
"engines": {
|
|
32
|
+
"node": ">=10.0.0"
|
|
33
|
+
},
|
|
34
|
+
"files": [
|
|
35
|
+
"browser.js",
|
|
36
|
+
"index.js",
|
|
37
|
+
"lib/*.js",
|
|
38
|
+
"wrapper.mjs"
|
|
39
|
+
],
|
|
40
|
+
"scripts": {
|
|
41
|
+
"test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js",
|
|
42
|
+
"integration": "mocha --throw-deprecation test/*.integration.js",
|
|
43
|
+
"lint": "eslint . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\""
|
|
44
|
+
},
|
|
45
|
+
"peerDependencies": {
|
|
46
|
+
"bufferutil": "^4.0.1",
|
|
47
|
+
"utf-8-validate": ">=5.0.2"
|
|
48
|
+
},
|
|
49
|
+
"peerDependenciesMeta": {
|
|
50
|
+
"bufferutil": {
|
|
51
|
+
"optional": true
|
|
52
|
+
},
|
|
53
|
+
"utf-8-validate": {
|
|
54
|
+
"optional": true
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
"devDependencies": {
|
|
58
|
+
"benchmark": "^2.1.4",
|
|
59
|
+
"bufferutil": "^4.0.1",
|
|
60
|
+
"eslint": "^9.0.0",
|
|
61
|
+
"eslint-config-prettier": "^10.0.1",
|
|
62
|
+
"eslint-plugin-prettier": "^5.0.0",
|
|
63
|
+
"globals": "^16.0.0",
|
|
64
|
+
"mocha": "^8.4.0",
|
|
65
|
+
"nyc": "^15.0.0",
|
|
66
|
+
"prettier": "^3.0.0",
|
|
67
|
+
"utf-8-validate": "^6.0.0"
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import createWebSocketStream from './lib/stream.js';
|
|
2
|
+
import Receiver from './lib/receiver.js';
|
|
3
|
+
import Sender from './lib/sender.js';
|
|
4
|
+
import WebSocket from './lib/websocket.js';
|
|
5
|
+
import WebSocketServer from './lib/websocket-server.js';
|
|
6
|
+
|
|
7
|
+
export { createWebSocketStream, Receiver, Sender, WebSocket, WebSocketServer };
|
|
8
|
+
export default WebSocket;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "local-websocket-server",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"lockfileVersion": 3,
|
|
5
|
+
"requires": true,
|
|
6
|
+
"packages": {
|
|
7
|
+
"": {
|
|
8
|
+
"name": "local-websocket-server",
|
|
9
|
+
"version": "1.0.0",
|
|
10
|
+
"dependencies": {
|
|
11
|
+
"ws": "^8.18.0"
|
|
12
|
+
},
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=14.0.0"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"node_modules/ws": {
|
|
18
|
+
"version": "8.18.3",
|
|
19
|
+
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
|
|
20
|
+
"integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=10.0.0"
|
|
24
|
+
},
|
|
25
|
+
"peerDependencies": {
|
|
26
|
+
"bufferutil": "^4.0.1",
|
|
27
|
+
"utf-8-validate": ">=5.0.2"
|
|
28
|
+
},
|
|
29
|
+
"peerDependenciesMeta": {
|
|
30
|
+
"bufferutil": {
|
|
31
|
+
"optional": true
|
|
32
|
+
},
|
|
33
|
+
"utf-8-validate": {
|
|
34
|
+
"optional": true
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { WebSocketServer } from 'ws';
|
|
2
|
+
import { createServer } from 'http';
|
|
3
|
+
import { URL } from 'url';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Local WebSocket Server for PeerPigeon Development
|
|
7
|
+
*
|
|
8
|
+
* This server mimics the AWS WebSocket API Gateway functionality
|
|
9
|
+
* for local development and testing of the PeerPigeon mesh network.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const PORT = process.env.PORT || 3000;
|
|
13
|
+
const HOST = process.env.HOST || 'localhost';
|
|
14
|
+
|
|
15
|
+
// In-memory storage for connections and peer data
|
|
16
|
+
const connections = new Map(); // peerId -> WebSocket connection
|
|
17
|
+
const peerData = new Map(); // peerId -> { peerId, timestamp, data }
|
|
18
|
+
|
|
19
|
+
// Utility functions
|
|
20
|
+
function generateId() {
|
|
21
|
+
return Date.now().toString(36) + Math.random().toString(36).substr(2);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function validatePeerId(peerId) {
|
|
25
|
+
return typeof peerId === 'string' && /^[a-fA-F0-9]{40}$/.test(peerId);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function findClosestPeers(targetPeerId, allPeerIds, maxPeers = 3) {
|
|
29
|
+
if (!targetPeerId || !allPeerIds || allPeerIds.length === 0) {
|
|
30
|
+
return [];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// XOR distance calculation (simplified)
|
|
34
|
+
const distances = allPeerIds.map(peerId => {
|
|
35
|
+
let distance = 0;
|
|
36
|
+
const minLength = Math.min(targetPeerId.length, peerId.length);
|
|
37
|
+
|
|
38
|
+
for (let i = 0; i < minLength; i++) {
|
|
39
|
+
const xor = parseInt(targetPeerId[i], 16) ^ parseInt(peerId[i], 16);
|
|
40
|
+
distance += xor;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return { peerId, distance };
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
// Sort by distance and return closest peers
|
|
47
|
+
distances.sort((a, b) => a.distance - b.distance);
|
|
48
|
+
return distances.slice(0, maxPeers).map(item => item.peerId);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function getActivePeers(excludePeerId = null) {
|
|
52
|
+
const peers = [];
|
|
53
|
+
for (const [peerId, connection] of connections) {
|
|
54
|
+
if (peerId !== excludePeerId && connection.readyState === WebSocket.OPEN) {
|
|
55
|
+
peers.push(peerId);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return peers;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function sendToConnection(peerId, data) {
|
|
62
|
+
const connection = connections.get(peerId);
|
|
63
|
+
if (connection && connection.readyState === WebSocket.OPEN) {
|
|
64
|
+
try {
|
|
65
|
+
connection.send(JSON.stringify(data));
|
|
66
|
+
return true;
|
|
67
|
+
} catch (error) {
|
|
68
|
+
console.error(`Error sending to ${peerId}:`, error);
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function broadcastToClosestPeers(fromPeerId, message, maxPeers = 5) {
|
|
76
|
+
const activePeers = getActivePeers(fromPeerId);
|
|
77
|
+
const closestPeers = findClosestPeers(fromPeerId, activePeers, maxPeers);
|
|
78
|
+
|
|
79
|
+
console.log(`Broadcasting from ${fromPeerId} to ${closestPeers.length} closest peers`);
|
|
80
|
+
|
|
81
|
+
closestPeers.forEach(peerId => {
|
|
82
|
+
sendToConnection(peerId, message);
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function sendToSpecificPeer(targetPeerId, message) {
|
|
87
|
+
return sendToConnection(targetPeerId, message);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Create HTTP server
|
|
91
|
+
const server = createServer();
|
|
92
|
+
|
|
93
|
+
// Create WebSocket server
|
|
94
|
+
const wss = new WebSocketServer({ server });
|
|
95
|
+
|
|
96
|
+
console.log(`๐ Starting PeerPigeon WebSocket server...`);
|
|
97
|
+
|
|
98
|
+
wss.on('connection', (ws, req) => {
|
|
99
|
+
let peerId = null;
|
|
100
|
+
|
|
101
|
+
// Extract peerId from query parameters
|
|
102
|
+
const url = new URL(req.url, `http://${req.headers.host}`);
|
|
103
|
+
const queryPeerId = url.searchParams.get('peerId');
|
|
104
|
+
|
|
105
|
+
if (!queryPeerId || !validatePeerId(queryPeerId)) {
|
|
106
|
+
console.log(`โ Invalid peerId: ${queryPeerId}`);
|
|
107
|
+
ws.close(1008, 'Invalid peerId');
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
peerId = queryPeerId;
|
|
112
|
+
|
|
113
|
+
// Store connection
|
|
114
|
+
connections.set(peerId, ws);
|
|
115
|
+
peerData.set(peerId, {
|
|
116
|
+
peerId,
|
|
117
|
+
timestamp: Date.now(),
|
|
118
|
+
connected: true
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
console.log(`โ
Peer ${peerId.substring(0, 8)}... connected (${connections.size} total)`);
|
|
122
|
+
|
|
123
|
+
// Send connection confirmation
|
|
124
|
+
ws.send(JSON.stringify({
|
|
125
|
+
type: 'connected',
|
|
126
|
+
peerId: peerId,
|
|
127
|
+
timestamp: Date.now()
|
|
128
|
+
}));
|
|
129
|
+
|
|
130
|
+
// Handle incoming messages
|
|
131
|
+
ws.on('message', (data) => {
|
|
132
|
+
try {
|
|
133
|
+
const message = JSON.parse(data);
|
|
134
|
+
const { type, data: messageData, targetPeerId, maxPeers } = message;
|
|
135
|
+
|
|
136
|
+
console.log(`๐จ Received ${type} from ${peerId.substring(0, 8)}...`);
|
|
137
|
+
|
|
138
|
+
const responseMessage = {
|
|
139
|
+
type,
|
|
140
|
+
data: messageData,
|
|
141
|
+
fromPeerId: peerId,
|
|
142
|
+
targetPeerId,
|
|
143
|
+
timestamp: Date.now()
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
// Handle different message types
|
|
147
|
+
switch (type) {
|
|
148
|
+
case 'ping':
|
|
149
|
+
// Respond with pong
|
|
150
|
+
ws.send(JSON.stringify({
|
|
151
|
+
type: 'pong',
|
|
152
|
+
timestamp: Date.now(),
|
|
153
|
+
originalTimestamp: messageData?.timestamp
|
|
154
|
+
}));
|
|
155
|
+
break;
|
|
156
|
+
|
|
157
|
+
case 'announce':
|
|
158
|
+
// Handle peer announcement
|
|
159
|
+
peerData.set(peerId, {
|
|
160
|
+
peerId,
|
|
161
|
+
timestamp: Date.now(),
|
|
162
|
+
data: messageData,
|
|
163
|
+
connected: true
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
const activePeers = getActivePeers(peerId);
|
|
167
|
+
console.log(`๐ข Announcing ${peerId.substring(0, 8)}... to ${activePeers.length} peers`);
|
|
168
|
+
|
|
169
|
+
// Send peer-discovered messages to other peers
|
|
170
|
+
activePeers.forEach(otherPeerId => {
|
|
171
|
+
sendToConnection(otherPeerId, {
|
|
172
|
+
type: 'peer-discovered',
|
|
173
|
+
data: { peerId, ...messageData },
|
|
174
|
+
fromPeerId: 'system',
|
|
175
|
+
targetPeerId: otherPeerId,
|
|
176
|
+
timestamp: Date.now()
|
|
177
|
+
});
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
// Send existing peers to the new peer
|
|
181
|
+
activePeers.forEach(existingPeerId => {
|
|
182
|
+
const existingPeerData = peerData.get(existingPeerId);
|
|
183
|
+
ws.send(JSON.stringify({
|
|
184
|
+
type: 'peer-discovered',
|
|
185
|
+
data: { peerId: existingPeerId, ...existingPeerData?.data },
|
|
186
|
+
fromPeerId: 'system',
|
|
187
|
+
targetPeerId: peerId,
|
|
188
|
+
timestamp: Date.now()
|
|
189
|
+
}));
|
|
190
|
+
});
|
|
191
|
+
break;
|
|
192
|
+
|
|
193
|
+
case 'goodbye':
|
|
194
|
+
// Handle peer disconnect
|
|
195
|
+
peerData.delete(peerId);
|
|
196
|
+
broadcastToClosestPeers(peerId, responseMessage);
|
|
197
|
+
break;
|
|
198
|
+
|
|
199
|
+
case 'offer':
|
|
200
|
+
case 'answer':
|
|
201
|
+
case 'ice-candidate':
|
|
202
|
+
// Handle WebRTC signaling
|
|
203
|
+
if (targetPeerId) {
|
|
204
|
+
const success = sendToSpecificPeer(targetPeerId, responseMessage);
|
|
205
|
+
if (!success) {
|
|
206
|
+
console.log(`โ ๏ธ Failed to send ${type} to ${targetPeerId.substring(0, 8)}... (peer not found)`);
|
|
207
|
+
}
|
|
208
|
+
} else {
|
|
209
|
+
console.log(`โ ๏ธ ${type} message missing targetPeerId`);
|
|
210
|
+
}
|
|
211
|
+
break;
|
|
212
|
+
|
|
213
|
+
default:
|
|
214
|
+
// Handle generic messages
|
|
215
|
+
if (targetPeerId) {
|
|
216
|
+
sendToSpecificPeer(targetPeerId, responseMessage);
|
|
217
|
+
} else {
|
|
218
|
+
broadcastToClosestPeers(peerId, responseMessage, maxPeers || 10);
|
|
219
|
+
}
|
|
220
|
+
break;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
} catch (error) {
|
|
224
|
+
console.error(`โ Error handling message from ${peerId?.substring(0, 8)}...:`, error);
|
|
225
|
+
ws.send(JSON.stringify({
|
|
226
|
+
type: 'error',
|
|
227
|
+
error: 'Invalid message format',
|
|
228
|
+
timestamp: Date.now()
|
|
229
|
+
}));
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
// Handle connection close
|
|
234
|
+
ws.on('close', (code, reason) => {
|
|
235
|
+
console.log(`๐ Peer ${peerId?.substring(0, 8)}... disconnected (${code}: ${reason})`);
|
|
236
|
+
|
|
237
|
+
if (peerId) {
|
|
238
|
+
connections.delete(peerId);
|
|
239
|
+
peerData.delete(peerId);
|
|
240
|
+
|
|
241
|
+
// Notify other peers
|
|
242
|
+
const activePeers = getActivePeers();
|
|
243
|
+
activePeers.forEach(otherPeerId => {
|
|
244
|
+
sendToConnection(otherPeerId, {
|
|
245
|
+
type: 'peer-disconnected',
|
|
246
|
+
data: { peerId },
|
|
247
|
+
fromPeerId: 'system',
|
|
248
|
+
targetPeerId: otherPeerId,
|
|
249
|
+
timestamp: Date.now()
|
|
250
|
+
});
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
console.log(`๐ Active connections: ${connections.size}`);
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
// Handle connection errors
|
|
258
|
+
ws.on('error', (error) => {
|
|
259
|
+
console.error(`โ WebSocket error for ${peerId?.substring(0, 8)}...:`, error);
|
|
260
|
+
});
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
// Start server
|
|
264
|
+
server.listen(PORT, HOST, () => {
|
|
265
|
+
console.log(`๐ PeerPigeon WebSocket server running on ws://${HOST}:${PORT}`);
|
|
266
|
+
console.log(`๐ Usage: Connect with ?peerId=<40-char-hex-id>`);
|
|
267
|
+
console.log(`๐ Ready to handle peer connections...`);
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
// Handle graceful shutdown
|
|
271
|
+
process.on('SIGINT', () => {
|
|
272
|
+
console.log('\n๐ Shutting down WebSocket server...');
|
|
273
|
+
|
|
274
|
+
// Close all connections
|
|
275
|
+
for (const [peerId, connection] of connections) {
|
|
276
|
+
connection.close(1001, 'Server shutting down');
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// Close server
|
|
280
|
+
server.close(() => {
|
|
281
|
+
console.log('โ
WebSocket server closed');
|
|
282
|
+
process.exit(0);
|
|
283
|
+
});
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
// Error handling
|
|
287
|
+
process.on('uncaughtException', (error) => {
|
|
288
|
+
console.error('โ Uncaught Exception:', error);
|
|
289
|
+
process.exit(1);
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
process.on('unhandledRejection', (reason, promise) => {
|
|
293
|
+
console.error('โ Unhandled Rejection at:', promise, 'reason:', reason);
|
|
294
|
+
process.exit(1);
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
// Export for programmatic use
|
|
298
|
+
export { server, wss, connections, peerData };
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* WebSocket Server Test Script
|
|
5
|
+
*
|
|
6
|
+
* This script tests the local WebSocket server with multiple simulated peers.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { WebSocket } from 'ws';
|
|
10
|
+
|
|
11
|
+
// Configuration
|
|
12
|
+
const SERVER_URL = 'ws://localhost:3000';
|
|
13
|
+
const NUM_PEERS = 3;
|
|
14
|
+
const TEST_DURATION = 10000; // 10 seconds
|
|
15
|
+
|
|
16
|
+
// Generate a random 40-character hex peer ID
|
|
17
|
+
function generatePeerId() {
|
|
18
|
+
return Array.from({ length: 40 }, () => Math.floor(Math.random() * 16).toString(16)).join('');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Create a test peer
|
|
22
|
+
function createTestPeer(peerId, delay = 0) {
|
|
23
|
+
return new Promise((resolve) => {
|
|
24
|
+
setTimeout(() => {
|
|
25
|
+
const ws = new WebSocket(`${SERVER_URL}?peerId=${peerId}`);
|
|
26
|
+
|
|
27
|
+
ws.on('open', () => {
|
|
28
|
+
console.log(`โ
Peer ${peerId.substring(0, 8)}... connected`);
|
|
29
|
+
|
|
30
|
+
// Send announcement
|
|
31
|
+
ws.send(JSON.stringify({
|
|
32
|
+
type: 'announce',
|
|
33
|
+
data: { peerId }
|
|
34
|
+
}));
|
|
35
|
+
|
|
36
|
+
// Send periodic pings
|
|
37
|
+
const pingInterval = setInterval(() => {
|
|
38
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
39
|
+
ws.send(JSON.stringify({
|
|
40
|
+
type: 'ping',
|
|
41
|
+
data: { timestamp: Date.now() }
|
|
42
|
+
}));
|
|
43
|
+
} else {
|
|
44
|
+
clearInterval(pingInterval);
|
|
45
|
+
}
|
|
46
|
+
}, 5000);
|
|
47
|
+
|
|
48
|
+
resolve({ ws, peerId, pingInterval });
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
ws.on('message', (data) => {
|
|
52
|
+
try {
|
|
53
|
+
const message = JSON.parse(data);
|
|
54
|
+
console.log(`๐จ Peer ${peerId.substring(0, 8)}... received: ${message.type}`);
|
|
55
|
+
|
|
56
|
+
if (message.type === 'peer-discovered') {
|
|
57
|
+
console.log(`๐ Peer ${peerId.substring(0, 8)}... discovered: ${message.data.peerId.substring(0, 8)}...`);
|
|
58
|
+
}
|
|
59
|
+
} catch (error) {
|
|
60
|
+
console.error(`โ Parse error for ${peerId.substring(0, 8)}...:`, error);
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
ws.on('close', () => {
|
|
65
|
+
console.log(`๐ Peer ${peerId.substring(0, 8)}... disconnected`);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
ws.on('error', (error) => {
|
|
69
|
+
console.error(`โ Peer ${peerId.substring(0, 8)}... error:`, error.message);
|
|
70
|
+
});
|
|
71
|
+
}, delay);
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Main test function
|
|
76
|
+
async function runTest() {
|
|
77
|
+
console.log(`๐ Starting WebSocket server test with ${NUM_PEERS} peers`);
|
|
78
|
+
console.log(`๐ก Server URL: ${SERVER_URL}`);
|
|
79
|
+
console.log(`โฑ๏ธ Test duration: ${TEST_DURATION / 1000} seconds`);
|
|
80
|
+
console.log('');
|
|
81
|
+
|
|
82
|
+
// Create multiple test peers with staggered connections
|
|
83
|
+
const peers = [];
|
|
84
|
+
for (let i = 0; i < NUM_PEERS; i++) {
|
|
85
|
+
const peerId = generatePeerId();
|
|
86
|
+
const delay = i * 1000; // 1 second between connections
|
|
87
|
+
|
|
88
|
+
console.log(`๐ Creating peer ${i + 1}/${NUM_PEERS}: ${peerId.substring(0, 8)}... (delay: ${delay}ms)`);
|
|
89
|
+
|
|
90
|
+
try {
|
|
91
|
+
const peer = await createTestPeer(peerId, delay);
|
|
92
|
+
peers.push(peer);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
console.error(`โ Failed to create peer ${peerId.substring(0, 8)}...:`, error);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
console.log(`\n๐ Created ${peers.length} peers, running test for ${TEST_DURATION / 1000} seconds...`);
|
|
99
|
+
console.log('');
|
|
100
|
+
|
|
101
|
+
// Wait for test duration
|
|
102
|
+
await new Promise(resolve => setTimeout(resolve, TEST_DURATION));
|
|
103
|
+
|
|
104
|
+
// Cleanup
|
|
105
|
+
console.log('\n๐งน Cleaning up...');
|
|
106
|
+
peers.forEach(({ ws, peerId, pingInterval }) => {
|
|
107
|
+
clearInterval(pingInterval);
|
|
108
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
109
|
+
ws.send(JSON.stringify({
|
|
110
|
+
type: 'goodbye',
|
|
111
|
+
data: { peerId }
|
|
112
|
+
}));
|
|
113
|
+
ws.close();
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
console.log('โ
Test completed!');
|
|
118
|
+
process.exit(0);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Handle errors
|
|
122
|
+
process.on('uncaughtException', (error) => {
|
|
123
|
+
console.error('โ Uncaught Exception:', error);
|
|
124
|
+
process.exit(1);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
process.on('unhandledRejection', (reason, promise) => {
|
|
128
|
+
console.error('โ Unhandled Rejection at:', promise, 'reason:', reason);
|
|
129
|
+
process.exit(1);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
// Run the test
|
|
133
|
+
runTest().catch(console.error);
|