The background is that I’m trying to implement a simple websockets webserver than can both receive updates from clients and push updates to clients. I’m using the websocket crate for this. The websocket crate exposes the connection as a tokio_io::codec::Framed struct, which basically implements both the Sink and the Stream traits of the futures crate, the Sink trait being used to send data to the client and the Stream trait being used to receive data from clients.
The problem I keep running to is that I don’t understand how I can send data to clients (via the Sink trait) while I’m still trying to read data (via the Stream trait). It appears that the only way to receive data from a Stream is by converting it into a future (that resolves to the next element in the stream as well as the rest of the stream) or one of the abstractions built on the top of that, such as iterators. The problem is that converting the stream into a future consumes it, so I have no way to access it in any way, and while eventually I get it back (when the future resolves successfully or when it fails), in the meantime I have no means to push data to the client.
There appears to be no way to poll a stream for data without consuming it and getting a future that only resolves when the stream either receives some data or when it fails. There is a poll method exposed by the Stream trait, but my understanding it is that you’re not supposed to invoke that directly, similarly to how futures work.
It seems to me that this is a fairly basic use case for e.g. a web chat, which is typically the to-go example use of websockets, so I imagine there must be a way to do it, like a completely different approach or something, but I simply cannot find anything.
Has anyone ever ran into this or has any idea about how I should go about this? It’s kind of complicated so I apologize if my description is unclear, if that’s the case let me know and I will try to clarify it somehow.
EDIT: Quite apart from the problem described above, maybe it would be worth considering to exclude links to
docs.rs from the 2 links per post for new users limitation on this forum.