Examples » Core » Networking » Udp Sockets

Using UDP sockets for communication between a server and a client.

This example demonstrates how to set up a UDP server and client using the Cubos engine.

First, we need the network dependencies

#include <cubos/core/net/udp_socket.hpp>

We'll also define some dummy constants for demonstration purposes

#define SERVER_ADDRESS Address::LocalHost
#define SERVER_PORT 8080

#define CLIENT_ADDRESS Address::LocalHost
#define CLIENT_PORT 8081

Now, let's launch the UDP server, which will wait for a message and stop once it receives it

void runServer()
{
    UdpSocket server;
    CUBOS_INFO("Server is running and waiting for messages at port {}", SERVER_PORT);

    char buffer[1024];
    size_t received;
    Address senderAddress;
    while (true)
    {
        if (server.receive(buffer, sizeof(buffer), received, senderAddress))
        {
            buffer[received] = '\0'; // C strings :)
            CUBOS_INFO("Received message: {} with size {}", buffer, received);
            break;
        }

        CUBOS_ERROR("Receive error");
    }
}

Server is up, so let's create the UDP client which will send a message to the server

void runClient()
{
    UdpSocket client;
    CUBOS_ASSERT(client.bind(CLIENT_PORT, CLIENT_ADDRESS), "Failed to bind client socket");

    // sleep for a bit to make sure server is up before sending message
    std::this_thread::sleep_for(std::chrono::seconds(1));

    const char* msg = "Hello, I'm a Cubos UDP client!";
    if (!client.send(msg, std::strlen(msg), SERVER_ADDRESS, SERVER_PORT))
    {
        CUBOS_ERROR("Failed to send message");
        return;
    }

    CUBOS_INFO("Message sent to server");
}

Pretty easy huh? To finish off, let's launch them in separate threads

int main()
{
    std::thread serverThread(runServer);
    std::thread clientThread(runClient);

    serverThread.join();
    clientThread.join();

    return 0;
}

Output:

[15:14:06.503] [main.cpp:25 runServer] info: Server is running and waiting for messages at port 8080
[15:14:07.503] [main.cpp:60 runClient] info: Message sent to server
[15:14:07.503] [main.cpp:34 runServer] info: Received message: "Hello, I'm a Cubos UDP client!" with size 30