[solved] Webchat using rust-websocket


So I’m trying to create a webchat for multiple users to connect to using rust-websocket.

This seemed kinda simple to me since their examples already shows a small webchat. Problem with that is that their example chat creates a new chat room with every user that just echoes whatever the user writes. So I need to find some kind of way to let the users communicate with each other.

As my “base” to start from I am using server.rs example from rust-websocket and trying to connect to it using a simple js script like the websockets.html.

So now I need to make modifications that either allow me to (A:) group up every new user that connects and whenever a message is sent, iterate through the users and send them all the same message. Or (B:), which seems more reasonable to me, somehow get the message out of the receiving thread and then somehow make every thread send the message the one thread just received.

With other programming languages I would have tried to create arrays to hold the different clients that connect but it doesn’t seem to be that easy because of thread safety and moved variable issues. All I can find are ways to clone variables but that wouldn’t help out here since I couldn’t modify a variable I copied and then check if it got changed from another thread.

I appreciate rust’s memory and thread safety since I’m pretty sure I would have done something unsafe in any other programming language. But now my issue is that I don’t seem to find any way at all to solve this problem without trying (and prly failing) to write my own websocket library.

If anyone of you has ideas how to approach this problem please let me know. I hope I described my problem properly, if not, please let me know and I will try to rephrase it.





So this is not quite as straight-forward as I thought first.

Basically I used a dispatcher thread that would act like a control center for all the connected clients. So whenever a client receives a message it’s sent to the dispatcher and this then distributes the message to every connected client.

I also had to receive the messages in another thread because there is no non-blocking way to receive messages in rust-websocket. Then I ways able to just use a permanent loop that checks both for new messages received from the websocket and from the dispatcher.

Here’s how my code looked like in the end:

Thanks to mbrubeck from #rust for helping me out!