minetest_protocol/services/
client.rs

1use std::net::SocketAddr;
2
3use anyhow::bail;
4
5use super::socket::MinetestSocket;
6use crate::peer::peer::Peer;
7use crate::wire::command::*;
8
9pub struct MinetestClient {
10    remote_peer: Peer,
11}
12
13impl MinetestClient {
14    pub async fn connect(connect_to: SocketAddr) -> anyhow::Result<Self> {
15        let bind_addr = if connect_to.is_ipv4() {
16            "0.0.0.0:0".parse()?
17        } else {
18            "[::]:0".parse()?
19        };
20        let mut socket = MinetestSocket::new(bind_addr, false).await?;
21
22        // Send a null packet to server.
23        // It should answer back, establishing a peer ids.
24        let remote_peer = socket.add_peer(connect_to).await;
25
26        Ok(Self { remote_peer })
27    }
28
29    /// If this fails, the client has disconnected.
30    pub async fn recv(&mut self) -> anyhow::Result<ToClientCommand> {
31        match self.remote_peer.recv().await? {
32            Command::ToClient(cmd) => Ok(cmd),
33            Command::ToServer(_) => bail!("Invalid packet direction"),
34        }
35    }
36
37    /// If this fails, the client has disconnected.
38    pub async fn send(&mut self, command: ToServerCommand) -> anyhow::Result<()> {
39        self.remote_peer.send(Command::ToServer(command)).await
40    }
41}