peerpigeon 0.0.1 → 0.0.2
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/examples/browser/index.html +2 -2
- package/package.json +1 -1
- package/src/SignalingClient.js +2 -2
- package/websocket-server/README.md +0 -10
- package/websocket-server/server.js +1 -1
- package/examples/browser/app-dht-disabled.js +0 -42
- package/examples/browser/index-dht-disabled.html +0 -123
- package/examples/browser/ui-clean.js +0 -0
- package/websocket-server/memory-leak-test.js +0 -193
- package/websocket-server/test.js +0 -133
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
<p>WebRTC P2P mesh networking with XOR-based routing</p>
|
|
18
18
|
<div class="usage-hint">
|
|
19
19
|
<strong>Tip:</strong> You can pass the API Gateway URL via query parameter:<br>
|
|
20
|
-
<code>?api=
|
|
20
|
+
<code>?api=ws://localhost:3000</code>
|
|
21
21
|
</div>
|
|
22
22
|
</header>
|
|
23
23
|
|
|
@@ -183,7 +183,7 @@
|
|
|
183
183
|
<div class="input-group">
|
|
184
184
|
<label for="signaling-url">Signaling Server URL:</label>
|
|
185
185
|
<input type="url" id="signaling-url"
|
|
186
|
-
placeholder="
|
|
186
|
+
placeholder="ws://localhost:3000">
|
|
187
187
|
<small class="input-help">
|
|
188
188
|
Auto-populated from ?api, ?url, or ?signaling query parameters. Enter base API Gateway URL (without /signaling path).
|
|
189
189
|
</small>
|
package/package.json
CHANGED
package/src/SignalingClient.js
CHANGED
|
@@ -17,7 +17,7 @@ export class SignalingClient extends EventEmitter {
|
|
|
17
17
|
this.reconnectTimeout = null;
|
|
18
18
|
this.isReconnecting = false;
|
|
19
19
|
|
|
20
|
-
// Add keep-alive ping to prevent
|
|
20
|
+
// Add keep-alive ping to prevent WebSocket timeout
|
|
21
21
|
this.keepAliveInterval = null;
|
|
22
22
|
this.keepAliveIntervalMs = 9 * 60 * 1000; // Ping every 9 minutes for large safety margin
|
|
23
23
|
|
|
@@ -451,7 +451,7 @@ export class SignalingClient extends EventEmitter {
|
|
|
451
451
|
this.handleUnhealthyConnection();
|
|
452
452
|
}, this.connectionQualityTimeout);
|
|
453
453
|
|
|
454
|
-
// Send ping as a regular message (
|
|
454
|
+
// Send ping as a regular message (server will handle it)
|
|
455
455
|
this.websocket.send(JSON.stringify({
|
|
456
456
|
type: 'ping',
|
|
457
457
|
data: { peerId: this.peerId, timestamp: this.lastPingTime }
|
|
@@ -220,16 +220,6 @@ Browser Client 1 Browser Client 2 Browser Client N
|
|
|
220
220
|
(peers, connections)
|
|
221
221
|
```
|
|
222
222
|
|
|
223
|
-
## Comparison with AWS
|
|
224
|
-
|
|
225
|
-
| Feature | Local Server | AWS WebSocket |
|
|
226
|
-
|---------|-------------|---------------|
|
|
227
|
-
| Cost | Free | Pay per message |
|
|
228
|
-
| Scalability | Single machine | Auto-scaling |
|
|
229
|
-
| Persistence | In-memory | DynamoDB |
|
|
230
|
-
| Deployment | Local only | Global |
|
|
231
|
-
| Development | Instant | Deploy cycle |
|
|
232
|
-
|
|
233
223
|
## Troubleshooting
|
|
234
224
|
|
|
235
225
|
### Common Issues
|
|
@@ -5,7 +5,7 @@ import { URL } from 'url';
|
|
|
5
5
|
/**
|
|
6
6
|
* Local WebSocket Server for PeerPigeon Development
|
|
7
7
|
*
|
|
8
|
-
* This server
|
|
8
|
+
* This server provides WebSocket signaling functionality
|
|
9
9
|
* for local development and testing of the PeerPigeon mesh network.
|
|
10
10
|
*/
|
|
11
11
|
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
import { PeerPigeonMesh } from '../../src/PeerPigeonMesh.js';
|
|
2
|
-
import { PeerPigeonUI } from './ui.js';
|
|
3
|
-
|
|
4
|
-
class PeerPigeonApp {
|
|
5
|
-
constructor() {
|
|
6
|
-
// Test: Initialize mesh with WebDHT disabled to demonstrate the UI setting
|
|
7
|
-
this.mesh = new PeerPigeonMesh({ enableWebDHT: false });
|
|
8
|
-
|
|
9
|
-
// To enable WebDHT (default), use:
|
|
10
|
-
// this.mesh = new PeerPigeonMesh();
|
|
11
|
-
// this.mesh = new PeerPigeonMesh({ enableWebDHT: true });
|
|
12
|
-
|
|
13
|
-
this.ui = new PeerPigeonUI(this.mesh);
|
|
14
|
-
this.init();
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
async init() {
|
|
18
|
-
try {
|
|
19
|
-
await this.mesh.init();
|
|
20
|
-
this.ui.updateUI();
|
|
21
|
-
this.setupUnloadHandler();
|
|
22
|
-
} catch (error) {
|
|
23
|
-
console.error('Failed to initialize app:', error);
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
setupUnloadHandler() {
|
|
28
|
-
const handleUnload = () => {
|
|
29
|
-
if (this.mesh.connected) {
|
|
30
|
-
this.mesh.sendGoodbyeMessage();
|
|
31
|
-
}
|
|
32
|
-
};
|
|
33
|
-
|
|
34
|
-
window.addEventListener('beforeunload', handleUnload);
|
|
35
|
-
window.addEventListener('unload', handleUnload);
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
// Initialize the app when the page loads
|
|
40
|
-
document.addEventListener('DOMContentLoaded', () => {
|
|
41
|
-
new PeerPigeonApp();
|
|
42
|
-
});
|
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
<!DOCTYPE html>
|
|
2
|
-
<html lang="en">
|
|
3
|
-
<head>
|
|
4
|
-
<meta charset="UTF-8">
|
|
5
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
6
|
-
<title>PeerPigeon - DHT Disabled Demo</title>
|
|
7
|
-
<link rel="icon" type="image/png" href="assets/images/favicon.png">
|
|
8
|
-
<link rel="stylesheet" href="styles.css">
|
|
9
|
-
<style>
|
|
10
|
-
.demo-notice {
|
|
11
|
-
background: #fff3cd;
|
|
12
|
-
border: 1px solid #ffeaa7;
|
|
13
|
-
border-radius: 6px;
|
|
14
|
-
padding: 12px;
|
|
15
|
-
margin: 20px auto;
|
|
16
|
-
max-width: 600px;
|
|
17
|
-
text-align: center;
|
|
18
|
-
color: #856404;
|
|
19
|
-
font-weight: 500;
|
|
20
|
-
}
|
|
21
|
-
</style>
|
|
22
|
-
</head>
|
|
23
|
-
<body>
|
|
24
|
-
<div class="container">
|
|
25
|
-
<header>
|
|
26
|
-
<h1>
|
|
27
|
-
<img src="assets/images/pigeon.png" alt="PeerPigeon Logo">
|
|
28
|
-
PeerPigeon Demo - DHT Disabled
|
|
29
|
-
</h1>
|
|
30
|
-
<p>WebRTC-based peer-to-peer mesh networking with intelligent routing</p>
|
|
31
|
-
<div class="demo-notice">
|
|
32
|
-
🔧 <strong>Demo Mode:</strong> This demo shows PeerPigeon with WebDHT disabled.
|
|
33
|
-
Check the Settings section to see the DHT status indicator.
|
|
34
|
-
</div>
|
|
35
|
-
<div class="usage-hint">
|
|
36
|
-
<strong>Quick Start:</strong>
|
|
37
|
-
1. Open multiple browser tabs/windows with this page<br>
|
|
38
|
-
2. Enter a signaling server URL (or use <code>?api=your-api-gateway-url</code> in URL)<br>
|
|
39
|
-
3. Click Connect - all tabs will automatically discover and connect to each other<br>
|
|
40
|
-
4. Notice that DHT operations will show error messages since DHT is disabled
|
|
41
|
-
</div>
|
|
42
|
-
</header>
|
|
43
|
-
|
|
44
|
-
<main>
|
|
45
|
-
<!-- Include the same content as index.html but referencing the modified app.js -->
|
|
46
|
-
<!-- Copy the entire main content from index.html -->
|
|
47
|
-
<div class="peer-info">
|
|
48
|
-
<div class="section-header">
|
|
49
|
-
<h2>
|
|
50
|
-
<button id="peer-info-toggle" class="toggle-btn" aria-expanded="true">
|
|
51
|
-
▼ Peer Info
|
|
52
|
-
</button>
|
|
53
|
-
</h2>
|
|
54
|
-
</div>
|
|
55
|
-
<div id="peer-info-content" class="collapsible-content">
|
|
56
|
-
<div class="info-group">
|
|
57
|
-
<label>Peer ID:</label>
|
|
58
|
-
<span id="peer-id">Not initialized</span>
|
|
59
|
-
</div>
|
|
60
|
-
<div class="info-group">
|
|
61
|
-
<label>Status:</label>
|
|
62
|
-
<span id="status" class="status disconnected">Disconnected</span>
|
|
63
|
-
</div>
|
|
64
|
-
<div class="info-group">
|
|
65
|
-
<label>Connected Peers:</label>
|
|
66
|
-
<span id="peer-count">0</span>
|
|
67
|
-
</div>
|
|
68
|
-
<div class="input-group">
|
|
69
|
-
<label for="signaling-url-main">Signaling Server URL:</label>
|
|
70
|
-
<div class="input-group horizontal">
|
|
71
|
-
<input type="url" id="signaling-url-main"
|
|
72
|
-
placeholder="https://your-api-gateway.execute-api.region.amazonaws.com/dev">
|
|
73
|
-
<div class="button-group">
|
|
74
|
-
<button id="connect-btn" class="btn primary">Connect</button>
|
|
75
|
-
<button id="disconnect-btn" class="btn secondary" disabled>Disconnect</button>
|
|
76
|
-
</div>
|
|
77
|
-
</div>
|
|
78
|
-
<small class="input-help">
|
|
79
|
-
Auto-populated from ?api, ?url, or ?signaling query parameters
|
|
80
|
-
</small>
|
|
81
|
-
</div>
|
|
82
|
-
</div>
|
|
83
|
-
</div>
|
|
84
|
-
|
|
85
|
-
<!-- Rest of the UI components would go here... -->
|
|
86
|
-
<!-- For brevity, showing just the key Settings section -->
|
|
87
|
-
|
|
88
|
-
<div class="settings" aria-expanded="false">
|
|
89
|
-
<div class="section-header">
|
|
90
|
-
<h2>
|
|
91
|
-
<button id="settings-toggle" class="toggle-btn" aria-expanded="false">
|
|
92
|
-
▶ Settings
|
|
93
|
-
</button>
|
|
94
|
-
</h2>
|
|
95
|
-
</div>
|
|
96
|
-
<div id="settings-content" class="collapsible-content" style="display: none;">
|
|
97
|
-
<div class="input-group">
|
|
98
|
-
<label for="signaling-url">Signaling Server URL:</label>
|
|
99
|
-
<input type="url" id="signaling-url"
|
|
100
|
-
placeholder="https://your-api-gateway.execute-api.region.amazonaws.com/dev">
|
|
101
|
-
<small class="input-help">
|
|
102
|
-
Auto-populated from ?api, ?url, or ?signaling query parameters. Enter base API Gateway URL (without /signaling path).
|
|
103
|
-
</small>
|
|
104
|
-
</div>
|
|
105
|
-
|
|
106
|
-
<div class="auto-discovery-control">
|
|
107
|
-
<label class="checkbox-label">
|
|
108
|
-
<input type="checkbox" id="webdht-toggle" checked disabled>
|
|
109
|
-
<span class="checkmark"></span>
|
|
110
|
-
Enable WebDHT (Distributed Hash Table)
|
|
111
|
-
</label>
|
|
112
|
-
<small class="input-help">
|
|
113
|
-
WebDHT status (configured at startup, restart required to change)
|
|
114
|
-
</small>
|
|
115
|
-
</div>
|
|
116
|
-
</div>
|
|
117
|
-
</div>
|
|
118
|
-
</main>
|
|
119
|
-
</div>
|
|
120
|
-
|
|
121
|
-
<script type="module" src="app-dht-disabled.js"></script>
|
|
122
|
-
</body>
|
|
123
|
-
</html>
|
|
File without changes
|
|
@@ -1,193 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Memory Leak Test Script
|
|
5
|
-
*
|
|
6
|
-
* This script helps identify memory leaks by repeatedly connecting and disconnecting
|
|
7
|
-
* multiple peers, monitoring memory usage.
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
import { WebSocket } from 'ws';
|
|
11
|
-
|
|
12
|
-
// Configuration
|
|
13
|
-
const SERVER_URL = 'ws://localhost:3000';
|
|
14
|
-
const NUM_PEERS = 5;
|
|
15
|
-
const CYCLES = 10;
|
|
16
|
-
const CYCLE_DURATION = 5000; // 5 seconds per cycle
|
|
17
|
-
|
|
18
|
-
// Track memory usage
|
|
19
|
-
let initialMemory = 0;
|
|
20
|
-
let cycleCount = 0;
|
|
21
|
-
|
|
22
|
-
// Generate a random 40-character hex peer ID
|
|
23
|
-
function generatePeerId() {
|
|
24
|
-
return Array.from({ length: 40 }, () => Math.floor(Math.random() * 16).toString(16)).join('');
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
// Get memory usage
|
|
28
|
-
function getMemoryUsage() {
|
|
29
|
-
if (typeof process !== 'undefined' && process.memoryUsage) {
|
|
30
|
-
return process.memoryUsage().heapUsed / 1024 / 1024; // MB
|
|
31
|
-
}
|
|
32
|
-
return 0;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
// Create a test peer that will be disconnected
|
|
36
|
-
function createTestPeer(peerId) {
|
|
37
|
-
return new Promise((resolve, reject) => {
|
|
38
|
-
const ws = new WebSocket(`${SERVER_URL}?peerId=${peerId}`);
|
|
39
|
-
let pingInterval;
|
|
40
|
-
|
|
41
|
-
ws.on('open', () => {
|
|
42
|
-
console.log(`✅ Peer ${peerId.substring(0, 8)}... connected`);
|
|
43
|
-
|
|
44
|
-
// Send announcement
|
|
45
|
-
ws.send(JSON.stringify({
|
|
46
|
-
type: 'announce',
|
|
47
|
-
data: { peerId }
|
|
48
|
-
}));
|
|
49
|
-
|
|
50
|
-
// Send periodic pings
|
|
51
|
-
pingInterval = setInterval(() => {
|
|
52
|
-
if (ws.readyState === WebSocket.OPEN) {
|
|
53
|
-
ws.send(JSON.stringify({
|
|
54
|
-
type: 'ping',
|
|
55
|
-
data: { timestamp: Date.now() }
|
|
56
|
-
}));
|
|
57
|
-
}
|
|
58
|
-
}, 2000);
|
|
59
|
-
|
|
60
|
-
resolve({ ws, peerId, pingInterval });
|
|
61
|
-
});
|
|
62
|
-
|
|
63
|
-
ws.on('message', (data) => {
|
|
64
|
-
try {
|
|
65
|
-
const message = JSON.parse(data);
|
|
66
|
-
if (message.type === 'peer-discovered') {
|
|
67
|
-
console.log(`🔍 Peer ${peerId.substring(0, 8)}... discovered: ${message.data.peerId.substring(0, 8)}...`);
|
|
68
|
-
}
|
|
69
|
-
} catch (error) {
|
|
70
|
-
console.error(`❌ Parse error for ${peerId.substring(0, 8)}...:`, error);
|
|
71
|
-
}
|
|
72
|
-
});
|
|
73
|
-
|
|
74
|
-
ws.on('close', () => {
|
|
75
|
-
if (pingInterval) {
|
|
76
|
-
clearInterval(pingInterval);
|
|
77
|
-
}
|
|
78
|
-
console.log(`🔌 Peer ${peerId.substring(0, 8)}... disconnected`);
|
|
79
|
-
});
|
|
80
|
-
|
|
81
|
-
ws.on('error', (error) => {
|
|
82
|
-
if (pingInterval) {
|
|
83
|
-
clearInterval(pingInterval);
|
|
84
|
-
}
|
|
85
|
-
console.error(`❌ Peer ${peerId.substring(0, 8)}... error:`, error.message);
|
|
86
|
-
reject(error);
|
|
87
|
-
});
|
|
88
|
-
});
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
// Run a single cycle
|
|
92
|
-
async function runCycle() {
|
|
93
|
-
cycleCount++;
|
|
94
|
-
console.log(`\n🔄 Starting cycle ${cycleCount}/${CYCLES}`);
|
|
95
|
-
|
|
96
|
-
// Create peers
|
|
97
|
-
const peers = [];
|
|
98
|
-
for (let i = 0; i < NUM_PEERS; i++) {
|
|
99
|
-
const peerId = generatePeerId();
|
|
100
|
-
try {
|
|
101
|
-
const peer = await createTestPeer(peerId);
|
|
102
|
-
peers.push(peer);
|
|
103
|
-
} catch (error) {
|
|
104
|
-
console.error(`❌ Failed to create peer ${peerId.substring(0, 8)}...:`, error);
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
console.log(`📊 Created ${peers.length} peers`);
|
|
109
|
-
|
|
110
|
-
// Wait for cycle duration
|
|
111
|
-
await new Promise(resolve => setTimeout(resolve, CYCLE_DURATION));
|
|
112
|
-
|
|
113
|
-
// Disconnect all peers
|
|
114
|
-
console.log('🧹 Disconnecting all peers...');
|
|
115
|
-
peers.forEach(({ ws, peerId, pingInterval }) => {
|
|
116
|
-
if (pingInterval) {
|
|
117
|
-
clearInterval(pingInterval);
|
|
118
|
-
}
|
|
119
|
-
if (ws.readyState === WebSocket.OPEN) {
|
|
120
|
-
ws.send(JSON.stringify({
|
|
121
|
-
type: 'goodbye',
|
|
122
|
-
data: { peerId }
|
|
123
|
-
}));
|
|
124
|
-
ws.close();
|
|
125
|
-
}
|
|
126
|
-
});
|
|
127
|
-
|
|
128
|
-
// Wait for cleanup
|
|
129
|
-
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
130
|
-
|
|
131
|
-
// Check memory usage
|
|
132
|
-
const currentMemory = getMemoryUsage();
|
|
133
|
-
const memoryDelta = currentMemory - initialMemory;
|
|
134
|
-
|
|
135
|
-
console.log(`📈 Memory usage: ${currentMemory.toFixed(2)} MB (delta: ${memoryDelta > 0 ? '+' : ''}${memoryDelta.toFixed(2)} MB)`);
|
|
136
|
-
|
|
137
|
-
if (memoryDelta > 50) { // Alert if memory increased by more than 50MB
|
|
138
|
-
console.warn(`⚠️ Potential memory leak detected! Memory increased by ${memoryDelta.toFixed(2)} MB`);
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
// Main test function
|
|
143
|
-
async function runMemoryTest() {
|
|
144
|
-
console.log(`🚀 Starting memory leak test`);
|
|
145
|
-
console.log(`📡 Server URL: ${SERVER_URL}`);
|
|
146
|
-
console.log(`👥 Peers per cycle: ${NUM_PEERS}`);
|
|
147
|
-
console.log(`🔄 Cycles: ${CYCLES}`);
|
|
148
|
-
console.log(`⏱️ Cycle duration: ${CYCLE_DURATION / 1000} seconds`);
|
|
149
|
-
|
|
150
|
-
// Record initial memory
|
|
151
|
-
initialMemory = getMemoryUsage();
|
|
152
|
-
console.log(`📊 Initial memory usage: ${initialMemory.toFixed(2)} MB`);
|
|
153
|
-
|
|
154
|
-
// Run cycles
|
|
155
|
-
for (let i = 0; i < CYCLES; i++) {
|
|
156
|
-
try {
|
|
157
|
-
await runCycle();
|
|
158
|
-
} catch (error) {
|
|
159
|
-
console.error(`❌ Cycle ${i + 1} failed:`, error);
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
// Final memory check
|
|
164
|
-
const finalMemory = getMemoryUsage();
|
|
165
|
-
const totalDelta = finalMemory - initialMemory;
|
|
166
|
-
|
|
167
|
-
console.log(`\n📊 Final Results:`);
|
|
168
|
-
console.log(`Initial memory: ${initialMemory.toFixed(2)} MB`);
|
|
169
|
-
console.log(`Final memory: ${finalMemory.toFixed(2)} MB`);
|
|
170
|
-
console.log(`Total delta: ${totalDelta > 0 ? '+' : ''}${totalDelta.toFixed(2)} MB`);
|
|
171
|
-
|
|
172
|
-
if (totalDelta > 100) {
|
|
173
|
-
console.error(`❌ Memory leak detected! Total increase: ${totalDelta.toFixed(2)} MB`);
|
|
174
|
-
process.exit(1);
|
|
175
|
-
} else {
|
|
176
|
-
console.log(`✅ Memory usage appears stable (increase: ${totalDelta.toFixed(2)} MB)`);
|
|
177
|
-
process.exit(0);
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
// Handle errors
|
|
182
|
-
process.on('uncaughtException', (error) => {
|
|
183
|
-
console.error('❌ Uncaught Exception:', error);
|
|
184
|
-
process.exit(1);
|
|
185
|
-
});
|
|
186
|
-
|
|
187
|
-
process.on('unhandledRejection', (reason, promise) => {
|
|
188
|
-
console.error('❌ Unhandled Rejection at:', promise, 'reason:', reason);
|
|
189
|
-
process.exit(1);
|
|
190
|
-
});
|
|
191
|
-
|
|
192
|
-
// Run the test
|
|
193
|
-
runMemoryTest().catch(console.error);
|
package/websocket-server/test.js
DELETED
|
@@ -1,133 +0,0 @@
|
|
|
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);
|