-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnect_client.cpp
More file actions
62 lines (54 loc) · 1.57 KB
/
Copy pathconnect_client.cpp
File metadata and controls
62 lines (54 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include "rio/buffer.hpp"
#include "rio/io_context.hpp"
#include "rio/net/protocol.hpp"
#include "rio/net/socket.hpp"
#include "rio/task.hpp"
#include <chrono>
#include <cstdio>
using namespace rio;
using namespace rio::net;
using namespace std::chrono_literals;
static Task<void> DoConnect(IoContext& ctx) {
auto sock_result = Socket<Tcp>::Create(ctx, Tcp::V4());
if (!sock_result) {
std::printf("[client] socket create failed\n");
ctx.Stop();
co_return;
}
auto sock = std::move(*sock_result);
auto ep = Endpoint<Tcp>(AddressV4::Loopback(), 8080);
auto conn = co_await sock.AsyncConnect(ep, 3000ms);
if (!conn) {
std::printf("[client] connect failed: %s\n",
conn.error().ToString().c_str());
ctx.Stop();
co_return;
}
std::printf("[client] connected to 127.0.0.1:8080\n");
Buffer buf;
buf.Append("hello from rio client!\n");
auto w = co_await sock.AsyncWrite(buf);
if (!w) {
std::printf("[client] write failed\n");
ctx.Stop();
co_return;
}
std::printf("[client] sent %zu bytes\n", *w);
buf.Reset();
auto n = co_await sock.AsyncRead(buf, 3000ms);
if (!n) {
std::printf("[client] read failed: %s\n", n.error().ToString().c_str());
ctx.Stop();
co_return;
}
std::printf("[client] received: %.*s", static_cast<int>(buf.readableBytes()),
buf.readPos());
ctx.Stop();
}
// TCP client: 连接 127.0.0.1:8080,发送消息,接收回显
// 先启动 echo_server,再运行此程序
int main() {
auto ctx = std::move(*IoContext::Create());
Spawn(ctx, DoConnect(ctx));
ctx.Run();
}