rtc-examples 0.9.0

Examples of WebRTC.rs stack with SansIO RTC API
Documentation
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Perfect Negotiation Demo</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 900px;
            margin: 40px auto;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }

        .container {
            background: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
        }

        h1 {
            color: #333;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .role-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: bold;
            text-transform: uppercase;
        }

        .polite {
            background: #10b981;
            color: white;
        }

        .impolite {
            background: #f59e0b;
            color: white;
        }

        .subtitle {
            color: #666;
            margin-bottom: 30px;
            font-size: 14px;
            line-height: 1.6;
        }

        .status {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-weight: 500;
        }

        .status.disconnected {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #dc2626;
        }

        .status.connecting {
            background: #fef3c7;
            color: #92400e;
            border-left: 4px solid #f59e0b;
        }

        .status.connected {
            background: #d1fae5;
            color: #065f46;
            border-left: 4px solid #10b981;
        }

        .controls {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        button {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            flex: 1;
            min-width: 140px;
        }

        button:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        button:active:not(:disabled) {
            transform: translateY(0);
        }

        button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .btn-primary {
            background: #3b82f6;
            color: white;
        }

        .btn-primary:hover:not(:disabled) {
            background: #2563eb;
        }

        .btn-secondary {
            background: #8b5cf6;
            color: white;
        }

        .btn-secondary:hover:not(:disabled) {
            background: #7c3aed;
        }

        .btn-send {
            background: #10b981;
            color: white;
        }

        .btn-send:hover:not(:disabled) {
            background: #059669;
        }

        .message-area {
            margin-top: 20px;
        }

        .message-input {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }

        #messageInput {
            flex: 1;
            padding: 12px;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.2s;
        }

        #messageInput:focus {
            outline: none;
            border-color: #3b82f6;
        }

        .log {
            background: #f9fafb;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            padding: 15px;
            max-height: 300px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 13px;
        }

        .log-entry {
            padding: 6px 0;
            border-bottom: 1px solid #e5e7eb;
        }

        .log-entry:last-child {
            border-bottom: none;
        }

        .log-time {
            color: #6b7280;
            margin-right: 8px;
        }

        .log-level {
            font-weight: bold;
            margin-right: 8px;
        }

        .log-level.info {
            color: #3b82f6;
        }

        .log-level.success {
            color: #10b981;
        }

        .log-level.warning {
            color: #f59e0b;
        }

        .log-level.error {
            color: #ef4444;
        }

        .info-box {
            background: #eff6ff;
            border: 2px solid #bfdbfe;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }

        .info-box h3 {
            margin: 0 0 10px 0;
            color: #1e40af;
            font-size: 16px;
        }

        .info-box ul {
            margin: 0;
            padding-left: 20px;
            color: #1e3a8a;
            font-size: 14px;
            line-height: 1.8;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>
        Perfect Negotiation Demo
        <span class="role-badge" id="roleBadge"></span>
    </h1>
    <div class="subtitle">
        Demonstrating the Perfect Negotiation pattern at application level using webrtc-rs/rtc sans-I/O API
    </div>

    <div class="info-box">
        <h3>🎯 About Perfect Negotiation</h3>
        <ul>
            <li><strong>Both peers use identical code</strong> - no offerer/answerer asymmetry</li>
            <li><strong>Automatic collision detection</strong> - handles simultaneous offers gracefully</li>
            <li><strong>Polite/impolite roles</strong> - polite peer yields on collision</li>
            <li><strong>Application-level pattern</strong> - implemented using spec-compliant RTC primitives</li>
        </ul>
    </div>

    <div class="status disconnected" id="status">
        Status: Disconnected
    </div>

    <div class="controls">
        <button class="btn-primary" id="connectBtn" onclick="connect()">
            Connect
        </button>
        <button class="btn-secondary" id="renegotiateBtn" onclick="renegotiate()" disabled>
            Renegotiate
        </button>
    </div>

    <div class="message-area">
        <div class="message-input">
            <input type="text" id="messageInput" placeholder="Type a message..." disabled>
            <button class="btn-send" id="sendBtn" onclick="sendMessage()" disabled>
                Send
            </button>
        </div>

        <div class="log" id="log">
            <div class="log-entry">
                <span class="log-time">[00:00:00]</span>
                <span class="log-level info">[INFO]</span>
                Ready to connect...
            </div>
        </div>
    </div>
</div>

<script>
    // Determine role from URL path
    const isPolite = window.location.pathname === '/polite';
    const role = isPolite ? 'POLITE' : 'IMPOLITE';

    document.getElementById('roleBadge').className = `role-badge ${isPolite ? 'polite' : 'impolite'}`;
    document.getElementById('roleBadge').textContent = role;

    let ws = null;

    // Connect to WebSocket server (Rust backend handles WebRTC)
    function setupWebSocket() {
        ws = new WebSocket('ws://localhost:8081');

        ws.onopen = () => {
            log('Connected to signaling server', 'success');
        };

        ws.onmessage = async (event) => {
            const data = event.data;

            // Handle status updates from Rust backend
            try {
                const message = JSON.parse(data);

                if (message.type === 'status') {
                    updateStatus(message.state);
                    log(message.message, message.level || 'info');
                } else if (message.type === 'data') {
                    log(`Received: ${message.message}`, 'success');
                } else if (message.type === 'log') {
                    log(message.message, message.level || 'info');
                }
            } catch (e) {
                // Plain text message
                log(data, 'info');
            }
        };

        ws.onerror = (error) => {
            log('WebSocket error: ' + error, 'error');
        };

        ws.onclose = () => {
            log('Disconnected from signaling server', 'warning');
            updateStatus('disconnected');
        };
    }

    // Connect button handler - send command to Rust backend
    async function connect() {
        if (!ws || ws.readyState !== WebSocket.OPEN) {
            setupWebSocket();
            await new Promise(resolve => {
                const checkInterval = setInterval(() => {
                    if (ws && ws.readyState === WebSocket.OPEN) {
                        clearInterval(checkInterval);
                        resolve();
                    }
                }, 100);
            });
        }

        log('Sending connect command to Rust backend...', 'info');
        document.getElementById('connectBtn').disabled = true;

        // Send connect command to Rust
        ws.send('connect');
    }

    // Renegotiate button handler
    async function renegotiate() {
        if (ws && ws.readyState === WebSocket.OPEN) {
            log('Sending renegotiate command...', 'info');
            ws.send('renegotiate');
        } else {
            log('Not connected to server', 'error');
        }
    }

    // Send message through Rust backend
    function sendMessage() {
        const input = document.getElementById('messageInput');
        const message = input.value.trim();

        if (message && ws && ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify({
                type: 'message',
                message: message
            }));
            log(`Sent: ${message}`, 'info');
            input.value = '';
        }
    }

    // Handle Enter key in message input
    document.getElementById('messageInput').addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });

    // Update status display
    function updateStatus(state) {
        const statusDiv = document.getElementById('status');
        statusDiv.className = 'status';

        switch (state) {
            case 'connected':
                statusDiv.className += ' connected';
                statusDiv.textContent = 'Status: Connected ✓';
                document.getElementById('connectBtn').disabled = true;
                document.getElementById('renegotiateBtn').disabled = false;
                document.getElementById('messageInput').disabled = false;
                document.getElementById('sendBtn').disabled = false;
                break;
            case 'connecting':
                statusDiv.className += ' connecting';
                statusDiv.textContent = 'Status: Connecting...';
                document.getElementById('connectBtn').disabled = true; // Also disable during connection
                break;
            default:
                statusDiv.className += ' disconnected';
                statusDiv.textContent = 'Status: Disconnected';
                document.getElementById('connectBtn').disabled = false; // Re-enable on disconnect
                document.getElementById('renegotiateBtn').disabled = true;
                document.getElementById('messageInput').disabled = true;
                document.getElementById('sendBtn').disabled = true;
        }
    }

    // Log message to console
    function log(message, level = 'info') {
        const logDiv = document.getElementById('log');
        const time = new Date().toLocaleTimeString();
        const entry = document.createElement('div');
        entry.className = 'log-entry';
        entry.innerHTML = `
                <span class="log-time">[${time}]</span>
                <span class="log-level ${level}">[${level.toUpperCase()}]</span>
                ${message}
            `;
        logDiv.appendChild(entry);
        logDiv.scrollTop = logDiv.scrollHeight;

        // Also log to browser console
        console.log(`[${role}] ${message}`);
    }

    // Initialize - connect WebSocket immediately when page loads
    log(`Starting as ${role} peer`, 'info');
    log('Connecting to Rust backend...', 'info');
    setupWebSocket();
</script>
</body>
</html>