Quick example of opening sockets and files and doing some I/O on them.
#include <asm-generic/errno.h>
#include <cassert>
#include <cstdio>
#include <fcntl.h>
#include <future>
#include <sys/socket.h>
#include <unistd.h>
#include "uringpp/event_loop.h"
#include "uringpp/tcp_listener.h"
#include <uringpp/uringpp.h>
char buf[1024];
int n = 0;
while ((n = co_await socket.recv(buf, sizeof(buf))) > 0) {
co_await socket.send(buf, n, MSG_NOSIGNAL);
}
::printf("client fd=%d disconnected n=%d\n", socket.fd(), n);
};
while (true) {
auto [addr, socket] = co_await listener.accept();
::printf("accepted connection fd=%d from %s:%d\n", socket.fd(),
addr.ip().c_str(), addr.port());
handler(std::move(socket)).detach();
}
}
::printf("connected fd=%d\n", socket.fd());
char const *request =
"GET / HTTP/1.1\r\nHost: baidu.com\r\nUser-Agent: uringpp/0.1\r\nAccept: "
"*/*\r\nConnection: close\r\n\r\n";
co_await socket.send(request, ::strlen(request));
char buf[1024];
int n = 0;
while ((n = co_await socket.recv(buf, sizeof(buf))) > 0) {
co_await loop->write(STDOUT_FILENO, buf, n, 0);
}
co_await socket.shutdown(SHUT_RDWR);
co_await socket.close();
::printf("disconnected\n");
}
::printf("Open file\n");
char buf[4096];
::printf("Read file\n");
co_await file.read(buf, sizeof(buf), 0);
::printf("%s\n", buf);
::printf("Close file\n");
}
int main() {
auto loop = uringpp::event_loop::create();
loop->block_on(read_file(loop));
http_client(loop).detach();
loop->block_on(echo_server(loop));
return 0;
}
static task< file > open(std::shared_ptr< event_loop > loop, char const *path, int flags, mode_t mode)
Opens a file in the current working directory.
Definition: file.h:43
static task< socket > connect(std::shared_ptr< event_loop > loop, std::string const &hostname, std::string const &port)
Connect to a remote host.
Definition: socket.h:79
static tcp_listener listen(std::shared_ptr< event_loop > loop, std::string const &hostname, std::string const &port, int backlog=128)
Listen for incoming TCP connections on the given address. It will create a socket and bind it to the ...
Definition: tcp_listener.h:47