UDP Networking Example

Caution

No Production/Ready to use code is provided here, this is just code to show how networking with amethyst can be done.

Minecraft Bedrock Edition is an uwp (Universal Windows Platform) app, that means it is mostly sandboxed and doesn’t have access to most windows apis.
We normally use a windows lib like winsock for windows to connected to/create servers.
But due to it being an uwp app, we need to use the winrt.
 1winrt::Windows::Foundation::IAsyncAction send_packet(std::string data)
 2{
 3    try
 4    {
 5        // If the socket is not already connected, connect to the local server on port 12345
 6        if (!local_socket.Information().LocalAddress())
 7    {
 8        co_await local_socket.ConnectAsync(winrt::Windows::Networking::HostName(L"127.0.0.1"), L"12345");
 9    }
10
11    // Create a message to send
12    std::wstring message(data.begin(), data.end());
13    winrt::Windows::Storage::Streams::DataWriter writer;
14    writer.WriteString(message);
15
16    // Send the message
17    co_await local_socket.OutputStream().WriteAsync(writer.DetachBuffer());
18
19    writer.Close();
20
21    std::wcout << L"Message sent successfully!" << std::endl;
22    }
23        catch (winrt::hresult_error const& ex)
24    {
25        std::wcerr << L"Error: " << ex.message().c_str() << std::endl;
26    }
27}