Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Any way to check for incoming messages instead of waiting #441

Closed
Antosser opened this issue Sep 5, 2024 · 2 comments
Closed

Any way to check for incoming messages instead of waiting #441

Antosser opened this issue Sep 5, 2024 · 2 comments

Comments

@Antosser
Copy link

Antosser commented Sep 5, 2024

I am trying to make a chat API, where the user sends a message to the API to send a message, and the API sends a message to the user to tell them about an incoming message.

So, I want to both listen for incoming messages and have the ability to send them. But since write() takes a mutable reference, I cannot have a read() on a separate thread, and I couldn't find a method to check if a message had come in.

What am I missing? Seems like a common use case

@agalakhov
Copy link
Member

TL;DR: Use Tokio.

The problem you're facing is not really related to Tungstenite. You'll get exactly the same problem with just plain TcpStream from the standard library. And there is a very good reason why it is designed in such a way.

You need some kind of task planner in order to do that since you can't read and write at the same time in the same thread. And this is not so straightforward. A low-hanging fruit is to just start two threads, and it would kinda "work" in languages like C++, but it is prone to race conditions, and Rust will reject such attempts. Your code has to be smart enough to decide when it is safe to write and to read and in which order.

Fortunately, there are many readily-made options to do that. Most users choose Tokio here. We provide a binding named tokio-tungstenite for it. There are other bindings like async-tungstenite and many others for specific web frameworks.

@Antosser
Copy link
Author

Antosser commented Sep 6, 2024

Alright, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants