A socket class provides asynchronous IO operation and co_await
support
- VS 2017 15.6.1 or later
- Windows SDK 10.0.16299.0 or later
// Server
Socket socket(EAddressFamily::InternetworkV4, ESocketType::Stream, EProtocolType::Tcp);
socket.Bind("0.0.0.0", 1568);
socket.Listen(128);
auto acceptFuture = socket.AcceptAsync();
try
{
std::byte buffer[2] = { std::byte(1), std::byte(2) };
auto clientSocket = co_await acceptFuture;
co_await clientSocket.SendAsync(buffer);
co_await clientSocket.ReceiveAsync(buffer);
}
catch (const SocketError& /* e */)
{
printf("server exception\n");
}
// Client
Socket client(EAddressFamily::InternetworkV4, ESocketType::Stream, EProtocolType::Tcp);
co_await client.ConnectAsync("127.0.0.1", 1568);
std::byte buffer[2] = { std::byte(3), std::byte(4) };
co_await client.SendAsync(buffer);
co_await client.ReceiveAsync(buffer);
- Bind
- Listen
- AcceptAsync
- ConnectAsync
- ReceiveAsync
- SendAsync
- ReceiveLineAsync
- Dispose
- Then
- Wait
- WaitFor
- WaitUntil
- Get
- GetFor
- GetUntil
- WaitAll
- WaitForAll
- WaitUntilAll
socket.Bind(std::string ipAddress, int port);
socket.Listen(int backLog);
Async::Awaiter<Socket> future = socket.AcceptAsync();
Socket client = co_await future;
// or
auto future = co_await socket.AcceptAsync();
co_await socket.ConnectAsync();
std::byte* buf = new std::byte[100];
socket.ReceiveAsync(buf, 100);
// or
std::byte buf[100];
socket.ReceiveAsync(buf);
std::byte* buf = new std::byte[100];
// TODO: fill the buffer
co_await socket.SendAsync(buf, 100);
// or
std::byte buf[100];
// TODO: fill the buffer
co_await socket.SendAsync(buf);
socket.Dispose();
awaiter.Then([]{
std::cout << "done" << std::endl;
};
awaiter.Wait();
#include <chrono>
using namespace std::chrono_literals;
awaiter.WaitFor(10s);
#include <chrono>
using namespace std::chrono_literals;
awaiter.WaitUntil(std::chrono::steady_clock::now() + 10s);