gpt4 book ai didi

rust - 如何从 tokio-proto 连接握手中检索信息?

转载 作者:行者123 更新时间:2023-11-29 08:18:52 24 4
gpt4 key购买 nike

我正在弄清楚如何使用 tokio-proto crate,特别是在建立连接时进行的握手。我从 official documentation 中得到了示例工作:

impl<T: AsyncRead + AsyncWrite + 'static> ClientProto<T> for ClientLineProto {
type Request = String;
type Response = String;

/// `Framed<T, LineCodec>` is the return value of `io.framed(LineCodec)`
type Transport = Framed<T, line::LineCodec>;
type BindTransport = Box<Future<Item = Self::Transport, Error = io::Error>>;

fn bind_transport(&self, io: T) -> Self::BindTransport {
// Construct the line-based transport
let transport = io.framed(line::LineCodec);

// Send the handshake frame to the server.
let handshake = transport.send("You ready?".to_string())
// Wait for a response from the server, if the transport errors out,
// we don't care about the transport handle anymore, just the error
.and_then(|transport| transport.into_future().map_err(|(e, _)| e))
.and_then(|(line, transport)| {
// The server sent back a line, check to see if it is the
// expected handshake line.
match line {
Some(ref msg) if msg == "Bring it!" => {
println!("CLIENT: received server handshake");
Ok(transport)
}
Some(ref msg) if msg == "No! Go away!" => {
// At this point, the server is at capacity. There are a
// few things that we could do. Set a backoff timer and
// try again in a bit. Or we could try a different
// remote server. However, we're just going to error out
// the connection.

println!("CLIENT: server is at capacity");
let err = io::Error::new(io::ErrorKind::Other, "server at capacity");
Err(err)
}
_ => {
println!("CLIENT: server handshake INVALID");
let err = io::Error::new(io::ErrorKind::Other, "invalid handshake");
Err(err)
}
}
});

Box::new(handshake)
}
}

但是官方文档只提到了没有状态信息的握手。有没有一种通用的方法可以从握手中检索和存储有用的数据?

例如,如果在握手过程中(在建立连接后的第一条消息中)服务器发送了一些稍后应该由客户端使用的 key ,ClientProto 实现应该如何查看该 key key ?它应该存储在哪里?

最佳答案

您可以将字段添加到 ClientLineProto,所以这应该有效:

pub struct ClientLineProto {
handshakes: Arc<Mutex<HashMap<String, String>>>
}

然后您可以引用它并根据需要存储数据:

let mut handshakes = self.handshakes.lock();
handshakes.insert(handshake_key, "Blah blah handshake data")

这种访问可以在 bind_transport() 中用于存储内容。然后,当您在 main() 函数中创建 Arc::Mutex::HashMap 时,您将可以访问 serve()< 中的所有内容 方法,这意味着您可以将它传递给服务对象实例化,然后握手将在 call() 期间可用。

关于rust - 如何从 tokio-proto 连接握手中检索信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44245753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com