aboutsummaryrefslogtreecommitdiff
path: root/minecraft-protocol/src/connection.rs
blob: 4fa1cde7706214866e21553094cc60ec2cce7aa7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
use crate::ServerIpAddress;
use bytes::BytesMut;
use tokio::{io::BufWriter, net::TcpStream};

pub enum PacketFlow {
    ClientToServer,
    ServerToClient,
}

pub struct Connection {
    pub flow: PacketFlow,
    pub stream: BufWriter<TcpStream>,
    /// The read buffer
    pub buffer: BytesMut,
}

impl Connection {
    pub async fn new(address: &ServerIpAddress) -> Result<Connection, String> {
        let ip = address.ip;
        let port = address.port;

        let stream = TcpStream::connect(format!("{}:{}", ip, port))
            .await
            .map_err(|_| "Failed to connect to server")?;

        // enable tcp_nodelay
        stream
            .set_nodelay(true)
            .expect("Error enabling tcp_nodelay");

        Ok(Connection {
            flow: PacketFlow::ClientToServer,
            stream: BufWriter::new(stream),
            // 4mb read buffer
            buffer: BytesMut::with_capacity(4 * 1024 * 1024),
        })
    }
}