TCP Chat Server
Build a real-time chat server using actors and streams for TCP handling.
Architecture
The chat server uses two actor types working together:
Message Broadcasting
When a user sends a message, it flows through the system:
Connection Lifecycle
Define Messages
messages.rs
rust1
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
ChatServer Actor
Manages all connected clients and handles message broadcasting:
chat_server.rs
rust1
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
ClientSession Actor
Handles individual TCP connections using cineyma's StreamHandler:
client_session.rs
rust1
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
Main Entry Point
main.rs
rust1
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
Running the Example
1
2
3
4
5
6
7
8
9
10
The full example is available in the cineyma repository under examples/chat/.
Key Concepts
StreamHandler
Automatically processes items from async streams (like TCP lines) as actor messages.
Actor per Connection
Each TCP connection gets its own actor, isolating failures and state.
try_send for Fire-and-Forget
Use try_send when you don't need to wait for a response, like broadcasting.
Lifecycle Hooks
started() and stopped() hooks handle registration and cleanup automatically.
