wynd 0.3.0

A simple websocket library for rust.
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
# Tutorial: Building a WebSocket Chat Server

This tutorial will guide you through building a complete WebSocket chat server using Wynd. We'll start with a simple echo server and gradually add features to create a full-featured chat application.

## Prerequisites

- Rust toolchain (stable) with edition 2021 or later
- Basic understanding of Rust async/await
- A WebSocket client for testing (we'll use `wscat`)

## Step 1: Project Setup

Create a new binary crate and add the necessary dependencies:

```bash
cargo new wynd-chat --bin
cd wynd-chat
cargo add wynd
cargo add tokio@1 --features tokio/macros,rt-multi-thread
```

## Step 2: Basic Echo Server

Let's start with a simple echo server to understand the basics:

```rust
use wynd::wynd::Wynd;

#[tokio::main]
async fn main() {
    let mut wynd = Wynd::new();

    wynd.on_connection(|conn| async move {
        println!("New connection established: {}", conn.id());

        conn.on_open(|handle| async move {
            println!("Connection {} is now open", handle.id());
            let _ = handle.send_text("Welcome to the echo server!").await;
        })
        .await;

        conn.on_text(|msg, handle| async move {
            println!("Echoing: {}", msg.data);
            let _ = handle.send_text(&format!("Echo: {}", msg.data)).await;
        });

        conn.on_close(|event| async move {
            println!("Connection closed: code={}, reason={}", event.code, event.reason);
        });
    });

    wynd.listen(8080, || {
        println!("Echo server listening on ws://localhost:8080");
    })
    .await
    .unwrap();
}
```

### Understanding the Code

1. **Server Creation**: `Wynd::new()` creates a new WebSocket server instance
2. **Connection Handler**: `on_connection()` is called whenever a client connects
3. **Event Handlers**: Each connection can have handlers for different events:
   - `on_open()`: Called when the WebSocket handshake completes
   - `on_text()`: Called when text messages are received
   - `on_close()`: Called when the connection is closed
4. **Message Sending**: `handle.send_text()` sends messages back to the client
5. **Server Start**: `listen()` starts the server on the specified port

### Testing

Run the server:

```bash
cargo run
```

In another terminal, connect with wscat:

```bash
npx wscat -c ws://localhost:8080
```

Send messages and see them echoed back!

## Step 3: Adding Connection Tracking

Now let's track all connected clients so we can broadcast messages:

```rust
use wynd::wynd::Wynd;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

#[tokio::main]
async fn main() {
    let mut wynd = Wynd::new();
    let clients: Arc<Mutex<HashMap<u64, Arc<wynd::conn::ConnectionHandle>>>> = Arc::new(Mutex::new(HashMap::new()));

    wynd.on_connection(|conn| async move {
        let clients = Arc::clone(&clients);

        conn.on_open(|handle| async move {
            let handle = Arc::new(handle);
            let id = handle.id();

            // Add client to our tracking
            {
                let mut clients = clients.lock().unwrap();
                clients.insert(id, Arc::clone(&handle));
            }

            println!("Client {} joined", id);
            let _ = handle.send_text("Welcome to the chat!").await;

            // Notify other clients
            broadcast_message(&clients, &format!("Client {} joined the chat", id), id).await;
        })
        .await;

        conn.on_text(|msg, handle| async move {
            let id = handle.id();
            println!("Client {} says: {}", id, msg.data);

            // Broadcast to all clients
            broadcast_message(&clients, &format!("Client {}: {}", id, msg.data), id).await;
        });

        conn.on_close(|event| async move {
            println!("Client disconnected: {}", event.reason);
        });
    });

    wynd.listen(8080, || {
        println!("Chat server listening on ws://localhost:8080");
    })
    .await
    .unwrap();
}

async fn broadcast_message(
    clients: &Arc<Mutex<HashMap<u64, Arc<wynd::conn::ConnectionHandle>>>>,
    message: &str,
    sender_id: u64,
) {
    // 1) Snapshot under lock
    let handles: Vec<Arc<wynd::conn::ConnectionHandle>> = {
        let guard = clients.lock().await;
        guard
            .iter()
            .filter_map(|(id, h)| (*id != sender_id).then(|| Arc::clone(h)))
            .collect()
    };
    // 2) Send without holding the lock
    for handle in handles {
        let _ = handle.send_text(message).await;
    }
}
```

### Key Changes

1. **Client Tracking**: We use a `HashMap` to store all connected clients
2. **Thread Safety**: `Arc<Mutex<>>` allows safe sharing between threads
3. **Broadcasting**: The `broadcast_message` function sends messages to all clients except the sender
4. **Connection Management**: We add clients when they connect and can remove them when they disconnect

## Step 4: Adding User Names

Let's add user names to make the chat more personal:

```rust
use wynd::wynd::Wynd;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

#[derive(Clone)]
struct ChatUser {
    name: String,
    handle: Arc<wynd::conn::ConnectionHandle>,
}

#[tokio::main]
async fn main() {
    let mut wynd = Wynd::new();
    let users: Arc<Mutex<HashMap<u64, ChatUser>>> = Arc::new(Mutex::new(HashMap::new()));

    wynd.on_connection(|conn| async move {
        let users = Arc::clone(&users);

        conn.on_open(|handle| async move {
            let id = handle.id();
            println!("Client {} connected", id);

            let _ = handle.send_text("Welcome! Please set your name with: /name <your_name>").await;
        })
        .await;

        conn.on_text(|msg, handle| async move {
            let id = handle.id();
            let text = msg.data.trim();

            if text.starts_with("/name ") {
                let name = text[6..].trim();
                if !name.is_empty() {
                    let user = ChatUser {
                        name: name.to_string(),
                        handle: Arc::new(handle),
                    };

                    {
                        let mut users = users.lock().unwrap();
                        users.insert(id, user.clone());
                    }

                    println!("Client {} is now known as {}", id, name);
                    let _ = user.handle.send_text(&format!("You are now known as {}", name)).await;

                    // Notify other users
                    broadcast_message(&users, &format!("{} joined the chat", name), id).await;
                } else {
                    let _ = handle.send_text("Please provide a valid name").await;
                }
            } else {
                // Regular message
                let users = users.lock().unwrap();
                if let Some(user) = users.get(&id) {
                    let message = format!("{}: {}", user.name, text);
                    println!("{}", message);
                    broadcast_message(&users, &message, id).await;
                } else {
                    let _ = handle.send_text("Please set your name first with: /name <your_name>").await;
                }
            }
        });

        conn.on_close(|event| async move {
            let users = users.lock().unwrap();
            if let Some(user) = users.get(&event.code) {
                println!("{} left the chat", user.name);
                broadcast_message(&users, &format!("{} left the chat", user.name), event.code).await;
            }
        });
    });

    wynd.listen(8080, || {
        println!("Named chat server listening on ws://localhost:8080");
    })
    .await
    .unwrap();
}

async fn broadcast_message(
    users: &Arc<Mutex<HashMap<u64, ChatUser>>>,
    message: &str,
    sender_id: u64,
) {
    let users = users.lock().unwrap();
    for (id, user) in users.iter() {
        if *id != sender_id {
            let _ = user.handle.send_text(message).await;
        }
    }
}
```

### New Features

1. **User Names**: Users can set their names with `/name <name>`
2. **Named Messages**: Messages show the sender's name
3. **Join/Leave Notifications**: Other users are notified when someone joins or leaves
4. **Command Handling**: The server recognizes `/name` as a special command

## Step 5: Adding More Commands

Let's add more useful commands:

```rust
use wynd::wynd::Wynd;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

#[derive(Clone)]
struct ChatUser {
    name: String,
    handle: Arc<wynd::conn::ConnectionHandle>,
}

#[tokio::main]
async fn main() {
    let mut wynd = Wynd::new();
    let users: Arc<Mutex<HashMap<u64, ChatUser>>> = Arc::new(Mutex::new(HashMap::new()));

    wynd.on_connection(|conn| async move {
        let users = Arc::clone(&users);

        conn.on_open(|handle| async move {
            let id = handle.id();
            println!("Client {} connected", id);

            let help_text = r#"
Welcome to the chat! Available commands:
- /name <name> - Set your display name
- /users - List all online users
- /help - Show this help message
- /quit - Disconnect from the server
"#;
            let _ = handle.send_text(help_text).await;
        })
        .await;

        conn.on_text(|msg, handle| async move {
            let id = handle.id();
            let text = msg.data.trim();

            if text.starts_with("/") {
                // Handle commands
                let parts: Vec<&str> = text.splitn(2, ' ').collect();
                match parts[0] {
                    "/name" => {
                        if parts.len() > 1 {
                            let name = parts[1].trim();
                            if !name.is_empty() {
                                let user = ChatUser {
                                    name: name.to_string(),
                                    handle: Arc::new(handle),
                                };

                                {
                                    let mut users = users.lock().unwrap();
                                    users.insert(id, user.clone());
                                }

                                println!("Client {} is now known as {}", id, name);
                                let _ = user.handle.send_text(&format!("You are now known as {}", name)).await;

                                broadcast_message(&users, &format!("{} joined the chat", name), id).await;
                            } else {
                                let _ = handle.send_text("Please provide a valid name").await;
                            }
                        } else {
                            let _ = handle.send_text("Usage: /name <your_name>").await;
                        }
                    }
                    "/users" => {
                        let users = users.lock().unwrap();
                        let user_list: Vec<String> = users.values().map(|u| u.name.clone()).collect();
                        let message = format!("Online users: {}", user_list.join(", "));
                        let _ = handle.send_text(&message).await;
                    }
                    "/help" => {
                        let help_text = r#"
Available commands:
- /name <name> - Set your display name
- /users - List all online users
- /help - Show this help message
- /quit - Disconnect from the server
"#;
                        let _ = handle.send_text(help_text).await;
                    }
                    "/quit" => {
                        let _ = handle.send_text("Goodbye!").await;
                        let _ = handle.close().await;
                    }
                    _ => {
                        let _ = handle.send_text("Unknown command. Type /help for available commands.").await;
                    }
                }
            } else {
                // Regular message
                let users = users.lock().unwrap();
                if let Some(user) = users.get(&id) {
                    let message = format!("{}: {}", user.name, text);
                    println!("{}", message);
                    broadcast_message(&users, &message, id).await;
                } else {
                    let _ = handle.send_text("Please set your name first with: /name <your_name>").await;
                }
            }
        });

        conn.on_close(|event| async move {
            let mut users = users.lock().unwrap();
            if let Some(user) = users.remove(&event.code) {
                println!("{} left the chat", user.name);
                broadcast_message(&users, &format!("{} left the chat", user.name), event.code).await;
            }
        });
    });

    wynd.listen(8080, || {
        println!("Advanced chat server listening on ws://localhost:8080");
    })
    .await
    .unwrap();
}

async fn broadcast_message(
    users: &Arc<Mutex<HashMap<u64, ChatUser>>>,
    message: &str,
    sender_id: u64,
) {
    let users = users.lock().unwrap();
    for (id, user) in users.iter() {
        if *id != sender_id {
            let _ = user.handle.send_text(message).await;
        }
    }
}
```

### New Commands

1. **`/users`**: Lists all online users
2. **`/help`**: Shows available commands
3. **`/quit`**: Allows users to disconnect gracefully
4. **Better Command Parsing**: More robust command handling

## Step 6: Error Handling

Let's add proper error handling:

```rust
use wynd::wynd::Wynd;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

#[derive(Clone)]
struct ChatUser {
    name: String,
    handle: Arc<wynd::conn::ConnectionHandle>,
}

#[tokio::main]
async fn main() {
    let mut wynd = Wynd::new();
    let users: Arc<Mutex<HashMap<u64, ChatUser>>> = Arc::new(Mutex::new(HashMap::new()));

    wynd.on_connection(|conn| async move {
        let users = Arc::clone(&users);

        conn.on_open(|handle| async move {
            let id = handle.id();
            println!("Client {} connected", id);

            let help_text = r#"
Welcome to the chat! Available commands:
- /name <name> - Set your display name
- /users - List all online users
- /help - Show this help message
- /quit - Disconnect from the server
"#;

            // Handle potential send errors
            match handle.send_text(help_text).await {
                Ok(()) => println!("Welcome message sent to client {}", id),
                Err(e) => eprintln!("Failed to send welcome message to client {}: {}", id, e),
            }
        })
        .await;

        conn.on_text(|msg, handle| async move {
            let id = handle.id();
            let text = msg.data.trim();

            if text.starts_with("/") {
                // Handle commands
                let parts: Vec<&str> = text.splitn(2, ' ').collect();
                match parts[0] {
                    "/name" => {
                        if parts.len() > 1 {
                            let name = parts[1].trim();
                            if !name.is_empty() {
                                let user = ChatUser {
                                    name: name.to_string(),
                                    handle: Arc::new(handle),
                                };

                                {
                                    let mut users = users.lock().unwrap();
                                    users.insert(id, user.clone());
                                }

                                println!("Client {} is now known as {}", id, name);

                                if let Err(e) = user.handle.send_text(&format!("You are now known as {}", name)).await {
                                    eprintln!("Failed to send name confirmation to client {}: {}", id, e);
                                }

                                broadcast_message(&users, &format!("{} joined the chat", name), id).await;
                            } else {
                                if let Err(e) = handle.send_text("Please provide a valid name").await {
                                    eprintln!("Failed to send error message to client {}: {}", id, e);
                                }
                            }
                        } else {
                            if let Err(e) = handle.send_text("Usage: /name <your_name>").await {
                                eprintln!("Failed to send usage message to client {}: {}", id, e);
                            }
                        }
                    }
                    "/users" => {
                        let users = users.lock().unwrap();
                        let user_list: Vec<String> = users.values().map(|u| u.name.clone()).collect();
                        let message = format!("Online users: {}", user_list.join(", "));

                        if let Err(e) = handle.send_text(&message).await {
                            eprintln!("Failed to send user list to client {}: {}", id, e);
                        }
                    }
                    "/help" => {
                        let help_text = r#"
Available commands:
- /name <name> - Set your display name
- /users - List all online users
- /help - Show this help message
- /quit - Disconnect from the server
"#;

                        if let Err(e) = handle.send_text(help_text).await {
                            eprintln!("Failed to send help to client {}: {}", id, e);
                        }
                    }
                    "/quit" => {
                        if let Err(e) = handle.send_text("Goodbye!").await {
                            eprintln!("Failed to send goodbye to client {}: {}", id, e);
                        }

                        if let Err(e) = handle.close().await {
                            eprintln!("Failed to close connection for client {}: {}", id, e);
                        }
                    }
                    _ => {
                        if let Err(e) = handle.send_text("Unknown command. Type /help for available commands.").await {
                            eprintln!("Failed to send error message to client {}: {}", id, e);
                        }
                    }
                }
            } else {
                // Regular message
                let users = users.lock().unwrap();
                if let Some(user) = users.get(&id) {
                    let message = format!("{}: {}", user.name, text);
                    println!("{}", message);
                    broadcast_message(&users, &message, id).await;
                } else {
                    if let Err(e) = handle.send_text("Please set your name first with: /name <your_name>").await {
                        eprintln!("Failed to send name request to client {}: {}", id, e);
                    }
                }
            }
        });

        conn.on_close(|event| async move {
            let mut users = users.lock().unwrap();
            if let Some(user) = users.remove(&event.code) {
                println!("{} left the chat", user.name);
                broadcast_message(&users, &format!("{} left the chat", user.name), event.code).await;
            }
        });
    });

    // Handle server-level errors
    wynd.on_error(|err| async move {
        eprintln!("Server error: {}", err);
    });

    // Handle server shutdown
    wynd.on_close(|| {
        println!("Chat server shutting down");
    });

    // Start the server with error handling
    match wynd.listen(8080, || {
        println!("Advanced chat server listening on ws://localhost:8080");
    })
    .await
    {
        Ok(()) => println!("Server ran successfully"),
        Err(e) => eprintln!("Server failed: {}", e),
    }
}

async fn broadcast_message(
    users: &Arc<Mutex<HashMap<u64, ChatUser>>>,
    message: &str,
    sender_id: u64,
) {
    let users = users.lock().unwrap();
    for (id, user) in users.iter() {
        if *id != sender_id {
            if let Err(e) = user.handle.send_text(message).await {
                eprintln!("Failed to broadcast message to client {}: {}", id, e);
            }
        }
    }
}
```

### Error Handling Improvements

1. **Send Error Handling**: All `send_text()` calls are wrapped in `match` statements
2. **Server Error Handler**: Added `on_error()` to handle server-level errors
3. **Graceful Shutdown**: Added `on_close()` for server shutdown handling
4. **Connection Error Logging**: Failed sends are logged but don't crash the server

## Testing Your Chat Server

1. **Start the server**: `cargo run`
2. **Connect multiple clients**:

   ```bash
   # Terminal 1
   npx wscat -c ws://localhost:8080

   # Terminal 2
   npx wscat -c ws://localhost:8080
   ```

3. **Set names**: `/name Alice` and `/name Bob`
4. **Send messages**: Type messages and see them broadcast
5. **Try commands**: `/users`, `/help`, `/quit`

## Next Steps

- **Persistence**: Save chat history to a database
- **Private Messages**: Add `/msg <user> <message>` for private messages
- **Rooms**: Create multiple chat rooms
- **File Sharing**: Add support for sending files
- **Authentication**: Add user authentication
- **Rate Limiting**: Prevent spam messages

## Summary

You've built a complete WebSocket chat server with:

- ✅ Real-time messaging
- ✅ User names and commands
- ✅ Broadcasting to all users
- ✅ Error handling
- ✅ Graceful connection management

This demonstrates the core concepts of building WebSocket applications with Wynd. The same patterns can be applied to build other real-time applications like games, collaborative tools, or live dashboards.