Blame view

examples/unix/undgramechosvr.cpp 1.23 KB
48b4c725   Peter M. Groen   Setting up Socket-pp
1
  #include <iostream>
18a2dbfb   Peter M. Groen   Fixed paths
2
3
  #include "socket-cpp/unix_dgram_socket.h"
  #include "socket-cpp/version.h"
48b4c725   Peter M. Groen   Setting up Socket-pp
4
5
6
7
8
9
10
11
12
13
  
  using namespace std;
  
  // --------------------------------------------------------------------------
  // The main thread creates the UDP socket, and then starts them running the
  // echo service in a loop.
  
  int main(int argc, char* argv[])
  {
  	cout << "Sample Unix-domain datagram echo server for 'sockpp' "
18a2dbfb   Peter M. Groen   Fixed paths
14
  		<< osdev::components::socket-cpp::SOCKPP_VERSION << '\n' << endl;
48b4c725   Peter M. Groen   Setting up Socket-pp
15
  
18a2dbfb   Peter M. Groen   Fixed paths
16
  	osdev::components::socket-cpp::socket_initializer sockInit;
48b4c725   Peter M. Groen   Setting up Socket-pp
17
  
18a2dbfb   Peter M. Groen   Fixed paths
18
  	osdev::components::socket-cpp::unix_dgram_socket sock;
48b4c725   Peter M. Groen   Setting up Socket-pp
19
20
21
22
23
  	if (!sock) {
  		cerr << "Error creating the socket: " << sock.last_error_str() << endl;
  		return 1;
  	}
  
18a2dbfb   Peter M. Groen   Fixed paths
24
  	if (!sock.bind(osdev::components::socket-cpp::unix_address("/tmp/undgramechosvr.sock"))) {
48b4c725   Peter M. Groen   Setting up Socket-pp
25
26
27
28
29
30
31
32
  		cerr << "Error binding the socket: " << sock.last_error_str() << endl;
  		return 1;
  	}
  
  	// Run the socket in this thread.
  	ssize_t n;
  	char buf[512];
  
18a2dbfb   Peter M. Groen   Fixed paths
33
  	osdev::components::socket-cpp::unix_address srcAddr;
48b4c725   Peter M. Groen   Setting up Socket-pp
34
35
36
37
38
39
40
41
42
43
  
  	cout << "Awaiting packets on: '" << sock.address() << "'" << endl;
  
  	// Read some data, also getting the address of the sender,
  	// then just send it back.
  	while ((n = sock.recv_from(buf, sizeof(buf), &srcAddr)) > 0)
  		sock.send_to(buf, n, srcAddr);
  
  	return 0;
  }