undgramecho.cpp
1.56 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
#include <iostream>
#include <string>
#include "socket-cpp/unix_dgram_socket.h"
using namespace std;
// --------------------------------------------------------------------------
int main(int argc, char* argv[])
{
osdev::components::socket-cpp::socket_initializer sockInit;
string cliAddr { "/tmp/undgramecho.sock" },
svrAddr { "/tmp/undgramechosvr.sock" };
osdev::components::socket-cpp::unix_dgram_socket sock;
// A Unix-domain UDP client needs to bind to its own address
// before it can send or receive packets
if (!sock.bind(osdev::components::socket-cpp::unix_address(cliAddr))) {
cerr << "Error connecting to client address at '" << cliAddr << "'"
<< "\n\t" << sock.last_error_str() << endl;
return 1;
}
// "Connect" to the server address. This is a convenience to set the
// default 'send_to' address, as there is no real connection.
if (!sock.connect(osdev::components::socket-cpp::unix_address(svrAddr))) {
cerr << "Error connecting to server at '" << svrAddr << "'"
<< "\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;
}