TCP Messenger | Rust

Micheal Keines
3 min readJun 20, 2022

--

I have written a Client-Server Messenger model that uses TCP to communicate, to better understand Network programming concepts and a bit of Threaded design using Standard Library

The Idea was simple, here is the Image

I wanted to write a server that could handle multiple clients and allow them to talk to each other, but it had to write a lot of abstraction over the client to make it choose whom to talk too and stuff, so i decided to start by making just two clients and let them talk to each other.

Server Struct is bit daunting to look at, but its just the Arc and Mutex to make them accessible over multiple threads, as two clients have to access this Listener in a given moment (same old lock and release)

Client Struct is simple it just takes in a TcpStream

This client struct is actually how the server handles the Users, Actual Users just hold an Stream that is sent by the server.

Core Logic:

Our server listens in a port for incoming connections, once it gets two users it will just read & write stuff from one stream to another

Once the clients get their streams, the server starts to read from both of the streams and if any data was read, it will write to the other client.

Server does this in a infinite loop until one of the client decided to end the connection by terminating.

The message max length is 250 chars

The server keeps reading the clients streams even if there is no message sent, this is bit efficient, might have improve this part.

This is the core logic of server, it has two thread continuously reading and writing from its stream to the other.

I have added 250millsec thread sleep just to make the read & write bit slower, the chances of missing a message is too low…

From User end, all the Incoming Messages are collected and stored in a Vector using separate thread and channel is used to get input from the user thus, not locking the main thread.

Complete code is available here.

This is complete for educational purpose, this method is not scalable in any way, but greatly helped me understand how TCP stream is handled and how threads can be used. Next time, i should be here with a scalable version of this same TCP messenger. Please do share your views and ideas on how that could be done and about my current version.

--

--