udpecho.cpp
1.28 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
#include <iostream>
#include <string>
#include "sockpp/udp_socket.h"
#include "sockpp/version.h"
using namespace std;
// --------------------------------------------------------------------------
int main(int argc, char* argv[])
{
cout << "Sample UDP echo client for 'sockpp' "
<< osdev::components::socket-cpp::SOCKPP_VERSION << '\n' << endl;
string host = (argc > 1) ? argv[1] : "localhost";
in_port_t port = (argc > 2) ? atoi(argv[2]) : 12345;
osdev::components::socket-cpp::socket_initializer sockInit;
osdev::components::socket-cpp::udp_socket sock;
if (!sock.connect(osdev::components::socket-cpp::inet_address(host, port))) {
cerr << "Error connecting to server at " << host << ":" << port
<< "\n\t" << sock.last_error_str() << endl;
return 1;
}
cout << "Created UDP socket at: " << sock.address() << endl;
string s, sret;
while (getline(cin, s) && !s.empty()) {
if (sock.send(s) != ssize_t(s.length())) {
cerr << "Error writing to the UDP socket: "
<< sock.last_error_str() << endl;
break;
}
sret.resize(s.length());
ssize_t n = sock.recv(&sret[0], s.length());
if (n != ssize_t(s.length())) {
cerr << "Error reading from UDP socket: "
<< sock.last_error_str() << endl;
break;
}
cout << sret << endl;
}
return (!sock) ? 1 : 0;
}