-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcp_stream.cpp
More file actions
349 lines (254 loc) · 9.61 KB
/
tcp_stream.cpp
File metadata and controls
349 lines (254 loc) · 9.61 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
#include "tcp_socket.h"
#include <thread>
#include <chrono>
#include <string>
#include <sstream>
#include <cstdio>
using namespace ipsockets;
#if true
// server and client work on IPv4 mode
static const ip_type_e cfg_ip_type = v4;
static const addr4_t cfg_server = "127.0.0.1:3000";
static const addr4_t cfg_client = "127.0.0.1:3000";
#else
// server and client work on IPv6 mode
static const ip_type_e cfg_ip_type = v6;
static const addr6_t cfg_server = "[::1]:3000";
static const addr6_t cfg_client = "[::1]:3000";
#endif
using tcp_server_t = tcp_socket_t<cfg_ip_type, socket_type_e::server>;
using tcp_client_t = tcp_socket_t<cfg_ip_type, socket_type_e::client>;
using tcp_stream_client_t = tcp_stream_t<cfg_ip_type, socket_type_e::client>;
log_e socket_log_level = log_e::error;
// ============================================================
// Example 1: Basic << and >> operators
// ============================================================
// Server reads lines, client sends lines using iostream operators.
bool shutdown_server { false };
tcp_server_t server_sock { socket_log_level };
void example_1_server () {
if (server_sock.open (cfg_server) != no_error)
return;
printf ("[server] listening on %s\n", cfg_server.to_str ().c_str ());
while (!shutdown_server) {
addr_t<cfg_ip_type> client_addr;
tcp_client_t accepted = server_sock.accept (client_addr);
if (accepted.state != state_e::state_opened)
continue;
printf ("[server] client connected: %s\n", client_addr.to_str ().c_str ());
// Wrap accepted socket into a stream
tcp_stream_client_t stream (std::move (accepted));
{ // --- Example: read with >> operator ---
std::string word;
stream >> word;
if (stream)
printf ("[server] received word: '%s'\n", word.c_str ());
}
{ // --- Example: read with std::getline ---
std::string line;
if (std::getline (stream, line))
printf ("[server] received line: '%s'\n", line.c_str ());
}
{ // --- Example: read number ---
int number = 0;
stream >> number;
if (stream)
printf ("[server] received number: %d\n", number);
}
{ // consume trailing newline after number
std::string rest;
std::getline (stream, rest);
}
{ // --- Example: read multi-word line ---
std::string line;
if (std::getline (stream, line))
printf ("[server] received full line: '%s'\n", line.c_str ());
}
// --- Example: send response using << ---
stream << "RESPONSE OK" << std::endl;
stream << "value=" << 42 << std::endl;
stream << "pi=" << 3.14159 << std::endl;
printf ("[server] response sent, closing connection\n");
// stream destructor flushes and the socket closes
}
printf ("[server] shutdown\n");
}
void example_1_client () {
// small delay to let server start
std::this_thread::sleep_for (std::chrono::milliseconds (200));
tcp_client_t sock (socket_log_level);
if (sock.open (cfg_client) != no_error) {
printf ("[client] failed to connect\n");
return;
}
// Wrap client socket into a stream
tcp_stream_client_t stream (std::move (sock));
printf ("[client] connected to %s\n", stream.remote_address ().to_str ().c_str ());
// --- Send data using << operator ---
stream << "Hello"; // Send a word (server reads with >>)
stream << " world_from_stream!" << '\n'; // Send rest of line (server reads with getline — reads until \n)
stream << 12345 << '\n'; // Send a number
stream << "This is a multi-word message with spaces" << '\n'; // Send a full line with spaces
stream << std::flush; // Flush to make sure everything is sent
printf ("[client] all data sent\n");
{ // --- Read response using >> and getline ---
std::string line;
while (std::getline (stream, line))
printf ("[client] received: '%s'\n", line.c_str ());
}
printf ("[client] done\n");
}
// ============================================================
// Example 2: Structured data exchange
// ============================================================
// Shows sending/receiving structured data through streams.
void example_2_server_handler (tcp_client_t accepted) {
tcp_stream_client_t stream (std::move (accepted));
// Read a command in format: "CMD arg1 arg2"
std::string cmd;
double a = 0, b = 0;
stream >> cmd >> a >> b;
if (!stream) {
printf ("[server2] failed to read command\n");
return;
}
printf ("[server2] command='%s' a=%.2f b=%.2f\n", cmd.c_str (), a, b);
// Compute and send result
double result = 0;
if (cmd == "ADD") result = a + b;
else if (cmd == "MUL") result = a * b;
else if (cmd == "SUB") result = a - b;
else {
stream << "ERROR unknown command" << std::endl;
return;
}
stream << "RESULT " << result << std::endl;
printf ("[server2] sent result: %.2f\n", result);
}
void example_2_server () {
tcp_server_t server (socket_log_level);
if (server.open ({cfg_client.ip, 3001}) != no_error)
return;
printf ("[server2] listening for calculator requests\n");
for (int i = 0; i < 3; i++) {
addr_t<cfg_ip_type> client_addr;
tcp_client_t accepted = server.accept (client_addr);
if (accepted.state == state_e::state_opened)
example_2_server_handler (std::move (accepted));
}
printf ("[server2] shutdown\n");
}
void example_2_client () {
std::this_thread::sleep_for (std::chrono::milliseconds (200));
// Send three calculator requests
struct { const char* cmd; double a; double b; } requests[] = {
{ "ADD", 10.5, 20.3 },
{ "MUL", 3.0, 7.0 },
{ "SUB", 100.0, 42.0 }
};
for (int i = 0; i < 3; i++) {
tcp_client_t sock (socket_log_level);
if (sock.open ({cfg_client.ip, 3001}) != no_error) {
printf ("[client2] failed to connect\n");
continue;
}
tcp_stream_client_t stream (std::move (sock));
// Send: "CMD a b\n"
stream << requests[i].cmd << ' ' << requests[i].a << ' ' << requests[i].b << std::endl;
// Read response line
std::string line;
if (std::getline (stream, line))
printf ("[client2] %s %.1f %.1f -> %s\n", requests[i].cmd, requests[i].a, requests[i].b, line.c_str ());
}
printf ("[client2] done\n");
}
// ============================================================
// Example 3: Line-by-line chat
// ============================================================
// Server echoes every line back in uppercase.
void example_3_server_handler (tcp_client_t accepted) {
tcp_stream_client_t stream (std::move (accepted));
std::string line;
while (std::getline (stream, line)) {
printf ("[echo-server] received: '%s'\n", line.c_str ());
if (line == "QUIT")
break;
// Convert to uppercase and echo back
for (char& c : line)
if ('a' <= c && c <= 'z')
c = c - 'a' + 'A';
stream << line << '\n';
}
stream << std::flush;
printf ("[echo-server] client disconnected\n");
}
void example_3_server () {
tcp_server_t server (socket_log_level);
if (server.open ({cfg_client.ip, 3002}) != no_error)
return;
printf ("[echo-server] listening\n");
addr_t<cfg_ip_type> client_addr;
tcp_client_t accepted = server.accept (client_addr);
if (accepted.state == state_e::state_opened)
example_3_server_handler (std::move (accepted));
printf ("[echo-server] shutdown\n");
}
void example_3_client () {
std::this_thread::sleep_for (std::chrono::milliseconds (200));
tcp_client_t sock (socket_log_level);
if (sock.open ({cfg_client.ip, 3002}) != no_error)
return;
tcp_stream_client_t stream (std::move (sock));
// Send several lines and read echoed responses
const char* messages[] = { "hello world", "ip-sockets-cpp-lite is great", "testing 123" };
for (const char* msg : messages) {
stream << msg << '\n';
stream << std::flush; // ensure data is sent before reading response
std::string response;
if (std::getline (stream, response))
printf ("[echo-client] sent='%s' received='%s'\n", msg, response.c_str ());
}
// Send quit command
stream << "QUIT" << std::endl;
printf ("[echo-client] done\n");
}
// ============================================================
// Main — run all examples sequentially
// ============================================================
int main () {
printf ("========================================\n");
printf (" Example 1: Basic iostream operators\n");
printf ("========================================\n\n");
{
std::thread server (example_1_server);
std::thread client (example_1_client);
client.join ();
shutdown_server = true;
server_sock.close ();
server.join ();
}
std::this_thread::sleep_for (std::chrono::milliseconds (500));
printf ("\n========================================\n");
printf (" Example 2: Calculator (structured)\n");
printf ("========================================\n\n");
{
std::thread server (example_2_server);
std::thread client (example_2_client);
client.join ();
server.join ();
}
std::this_thread::sleep_for (std::chrono::milliseconds (500));
printf ("\n========================================\n");
printf (" Example 3: Echo server (line-by-line)\n");
printf ("========================================\n\n");
{
std::thread server (example_3_server);
std::thread client (example_3_client);
client.join ();
server.join ();
}
printf ("\n========================================\n");
printf (" All examples completed!\n");
printf ("========================================\n");
return 0;
}