48b4c725
Peter M. Groen
Setting up Socket-pp
|
1
2
|
#include <iostream>
#include <string>
|
18a2dbfb
Peter M. Groen
Fixed paths
|
3
|
#include "socket-cpp/unix_dgram_socket.h"
|
48b4c725
Peter M. Groen
Setting up Socket-pp
|
4
5
6
7
8
9
10
|
using namespace std;
// --------------------------------------------------------------------------
int main(int argc, char* argv[])
{
|
18a2dbfb
Peter M. Groen
Fixed paths
|
11
|
osdev::components::socket-cpp::socket_initializer sockInit;
|
48b4c725
Peter M. Groen
Setting up Socket-pp
|
12
13
14
15
|
string cliAddr { "/tmp/undgramecho.sock" },
svrAddr { "/tmp/undgramechosvr.sock" };
|
18a2dbfb
Peter M. Groen
Fixed paths
|
16
|
osdev::components::socket-cpp::unix_dgram_socket sock;
|
48b4c725
Peter M. Groen
Setting up Socket-pp
|
17
18
19
20
|
// A Unix-domain UDP client needs to bind to its own address
// before it can send or receive packets
|
18a2dbfb
Peter M. Groen
Fixed paths
|
21
|
if (!sock.bind(osdev::components::socket-cpp::unix_address(cliAddr))) {
|
48b4c725
Peter M. Groen
Setting up Socket-pp
|
22
23
24
25
26
27
28
29
|
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.
|
18a2dbfb
Peter M. Groen
Fixed paths
|
30
|
if (!sock.connect(osdev::components::socket-cpp::unix_address(svrAddr))) {
|
48b4c725
Peter M. Groen
Setting up Socket-pp
|
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
|
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;
}
|