Sender and receiver channels with rust-websocket [previously tried ws-rs] crate


#1

I’m attempting setup a Connection with a Client handler for the ws-rs crate with two channels. One channel is for receiving and the other for sending messages on the websocket connection. I’m failing to understand how to setup the threads correctly to achieve this behavior. The examples from the crate do no seem to demonstrate how this could be done. Does anyone have suggestions or examples that would work for ws-rs or should look into using another crate?

Here is link to the GitHub issue and my current attempt in connection.rs.

GitHub Issue
GitHub Branch


#2

It’s not very clear exactly what code you had that didn’t compile - the inline compiler error and the commented out code makes it a bit hard to discern.

It looks like you might be missing a move for the closure you pass to connect. It also looks like you might be moving the receiver into the client thread closure but then also trying to move it to the Client value? A bit hard to tell with the code commented out.


#3

I’m looking for ideas or suggestions on how to go about writing tests for websocket connections. Specifically I’ll want to write a test for send_request(&self, request: raw_pb::Request) and recv_response(&mut self).

https://github.com/ttdonovan/sc2-api-rs/blob/ttdonovan/connection-send_ch/src/connection.rs

I’ve attempted ideas like setting up a mock server this but without much luck.

#[cfg(test)]
mod tests {
    use super::*;

    use std::thread::{self, JoinHandle};

    fn mock_server() -> JoinHandle<()> {
        thread::spawn(|| {
            use websocket::Message;
            use websocket::sync::Server;

            let server = Server::bind("127.0.0.1:5000").unwrap();

            for connection in server.filter_map(Result::ok) {
                thread::spawn(move || {
                    let mut client = connection.accept().unwrap();
                    let message = Message::text("Hello, client!");
                    let _ = client.send_message(&message);
                });
            }
        })
    }

    #[test]
    fn connection_test() {
        let server_thread = mock_server();

        let _conn = Connection::connect();
        let _ = server_thread.join();

        assert!(true);
    }
}