Comments (6)
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.
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.
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.
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.
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.
I would close this issue as there were no further discussions and IMO the question has been answered.
from tokio-tungstenite.
Related Issues (20)
- Consider closing stream if reader was dropped HOT 1
- Using a Tor connector from `arti-client` HOT 1
- Add feature to use rustls instead of native-tls HOT 1
- `TcpListener::accept` blocks runtime after accepting a websocket connection HOT 2
- What's Proper way to close a connection after split? HOT 1
- `tokio-tungstenite` + `SkipServerVerification` + `rustls ` seems never works HOT 2
- SendAfterClosing when doing the close handshake in 0.20.1 HOT 4
- Update to tungstenite 0.21 HOT 3
- `rustls-tls-native-roots` does not imply `rustls-tls-native-roots` for `tungstenite` HOT 3
- Passing body in `connect`? HOT 2
- Can we provided a way to keep the original header name case. HOT 1
- 403 Forbidden HOT 1
- "WebSocket protocol error: httparse error: invalid token" when connect from ngrok tcp tunnel. HOT 5
- Is it possible to bind client to specific interface? HOT 1
- 没有连接断开时,直接检测客户端的状态的api,以实现重新连接,这在其它语言中都是常见的
- Performance boost implementing `poll_write_vectored` and rustls 0.23 HOT 2
- Is MaybeTlsStream supposed to work for servers too? HOT 2
- 0.20 and 0.21 break something HOT 25
- Vectorized send HOT 2
- new rustls 0.23.x is incompatible with the 0.22.x used by tokio-tungstenite HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from tokio-tungstenite.