Giter Club home page Giter Club logo

Comments (6)

daniel-abramov avatar daniel-abramov commented on July 16, 2024

Well, you can copy the path value to your own variable inside the callback if you want. Or you can implement the callback's trait for your own structure and pass it as callback value to the function.

from tokio-tungstenite.

bbigras avatar bbigras commented on July 16, 2024

I used a struct and implemented Callback but I don't think I can modify the struct since self is not a reference in:

fn on_request(self, request: &Request) -> Result<Option<Vec<(String, String)>>>

Can I use a closure?

from tokio-tungstenite.

agalakhov avatar agalakhov commented on July 16, 2024

Yes you can. The clue is impl Callback for &mut MyObject. And it's already implemented for FnOnce. And every &mut FnMut is FnOnce.

from tokio-tungstenite.

bbigras avatar bbigras commented on July 16, 2024

Since you said MyObject I'm guessing I need to use a struct and not just a closure.

Something like this?

"it's already implemented for FnOnce. And every &mut FnMut is FnOnce" is confusing me tbh.

extern crate futures;
extern crate tokio_core;
extern crate tokio_tungstenite;
extern crate tungstenite;

use std::cell::RefCell;
use std::collections::HashMap;
use std::env;
use std::io::{Error, ErrorKind};
use std::rc::Rc;

use futures::Future;
use futures::stream::Stream;
use tokio_core::net::TcpListener;
use tokio_core::reactor::Core;
use tokio_tungstenite::accept_hdr_async;
use tungstenite::handshake::server::{Callback, Request};
use tungstenite::protocol::Message;

struct TestCallback {
    path: String,
}

impl<'a> Callback for &'a mut TestCallback {
    fn on_request(
        self,
        _request: &Request,
    ) -> tungstenite::error::Result<Option<Vec<(String, String)>>> {
        Ok(None)
    }
}

fn main() {
    let addr = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string());
    let addr = addr.parse().unwrap();

    // Create the event loop and TCP listener we'll accept connections on.
    let mut core = Core::new().unwrap();
    let handle = core.handle();
    let socket = TcpListener::bind(&addr, &handle).unwrap();
    println!("Listening on: {}", addr);

    // This is a single-threaded server, so we can just use Rc and RefCell to
    // store the map of all connections we know about.
    let connections = Rc::new(RefCell::new(HashMap::new()));

    let srv = socket.incoming().for_each(|(stream, addr)| {
        let connections_inner = connections.clone();
        let handle_inner = handle.clone();

        let test_callback = TestCallback {
            path: String::new(),
        };

        accept_hdr_async(stream, &mut test_callback)
            .and_then(move |ws_stream| {
                println!("New WebSocket connection: {}", addr);

                println!("test_callback: {:?}", test_callback.path);

                let (tx, rx) = futures::sync::mpsc::unbounded();
                connections_inner.borrow_mut().insert(addr, tx);

                let (sink, stream) = ws_stream.split();

                let connections = connections_inner.clone();
                let ws_reader = stream.for_each(move |message: Message| {
                    println!("Received a message from {}: {}", addr, message);

                    // For each open connection except the sender, send the
                    // string via the channel.
                    let mut conns = connections.borrow_mut();
                    let iter = conns
                        .iter_mut()
                        .filter(|&(&k, _)| k != addr)
                        .map(|(_, v)| v);
                    for tx in iter {
                        tx.unbounded_send(message.clone()).unwrap();
                    }
                    Ok(())
                });

                // Whenever we receive a string on the Receiver, we write it to
                // `WriteHalf<WebSocketStream>`.
                let ws_writer = rx.fold(sink, |mut sink, msg| {
                    use futures::Sink;
                    sink.start_send(msg).unwrap();
                    Ok(sink)
                });

                // Now that we've got futures representing each half of the socket, we
                // use the `select` combinator to wait for either half to be done to
                // tear down the other. Then we spawn off the result.
                let connection = ws_reader
                    .map(|_| ())
                    .map_err(|_| ())
                    .select(ws_writer.map(|_| ()).map_err(|_| ()));

                handle_inner.spawn(connection.then(move |_| {
                    connections_inner.borrow_mut().remove(&addr);
                    println!("Connection {} closed.", addr);
                    Ok(())
                }));

                Ok(())
            })
            .map_err(|e| {
                println!("Error during the websocket handshake occurred: {}", e);
                Error::new(ErrorKind::Other, e)
            })
    });

    // Execute server.
    core.run(srv).unwrap();
}
% cargo build                                                                                                                :(
   Compiling test-async v0.1.0 (file:///home/bbigras/dev/rust/test-async)
error[E0597]: `test_callback` does not live long enough
   --> src/main.rs:111:5
    |
55  |         accept_hdr_async(stream, &mut test_callback)
    |                                       ------------- borrow occurs here
...
111 |     });
    |     ^ `test_callback` dropped here while still borrowed
...
115 | }
    | - borrowed value needs to live until here

error: aborting due to previous error

error: Could not compile `test-async`.

To learn more, run the command again with --verbose.

from tokio-tungstenite.

daniel-abramov avatar daniel-abramov commented on July 16, 2024

accept_hdr_async is a future, that's why the compiler complains that your callback value does not live long enough. You can try to create a callback before the future (not inside the future) and/or use move to move the closure inside the future.

As a matter of fact, you can always move Rc<...> (or Rc<RefCell<...>>) inside a callback/future and use them to change your "runtime state" as the program runs (if you need one).

from tokio-tungstenite.

daniel-abramov avatar daniel-abramov commented on July 16, 2024

I would close this issue as there were no further discussions and IMO the question has been answered.

from tokio-tungstenite.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.