Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Connection Setup

In the previous chapter we looked at how to configure a certificate. This aspect is omitted in this chapter to prevent duplication. But remember that this is required to get your Endpoint up and running. This chapter explains how to set up a connection and prepare it for data transfer.

It all starts with the Endpoint struct, this is the entry point of the library.

Example

Let's start by defining some constants.

#![allow(unused)]
fn main() {
const SERVER_NAME: &str = "localhost";
const LOCALHOST_V4: IpAddr = IpAddr::V4(Ipv4Addr::LOCALHOST);
const CLIENT_ADDR: SocketAddr = SocketAddr::new(LOCALHOST_V4, 5000);
const SERVER_ADDR: SocketAddr = SocketAddr::new(LOCALHOST_V4, 5001);
}

Server

First, the server endpoint should be bound to a socket. The server() method, which can be used for this, returns the Endpoint type. Endpoint is used to start outgoing connections and accept incoming connections.

#![allow(unused)]
fn main() {
async fn server(config: ServerConfig) -> Result<(), Box<dyn Error>> {
    // Bind this endpoint to a UDP socket on the given server address.
    let endpoint = Endpoint::server(config, SERVER_ADDR)?;

    // Start iterating over incoming connections.
    while let Some(conn) = endpoint.accept().await {
        let connection = conn.await?;

        // Save connection somewhere, start transferring, receiving data, see DataTransfer tutorial.
    }

    Ok(())
}
}

Client

The client() returns only a Endpoint type. The client needs to connect to the server using the connect(server_name) method. The SERVER_NAME argument is the DNS name, matching the certificate configured in the server.

#![allow(unused)]
fn main() {
async fn client() -> Result<(), Box<dyn Error>> {
    // Bind this endpoint to a UDP socket on the given client address.
    let endpoint = Endpoint::client(CLIENT_ADDR)?;

    // Connect to the server passing in the server name which is supposed to be in the server certificate.
    let connection = endpoint.connect(SERVER_ADDR, SERVER_NAME)?.await?;

    // Start transferring, receiving data, see data transfer page.

    Ok(())
}
}



Next up, let's have a look at sending data over this connection.