Blame view

examples/udp/udpecho.cpp 1.28 KB
48b4c725   Peter M. Groen   Setting up Socket-pp
1
2
3
4
5
6
7
8
9
10
11
12
  #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' "
18a2dbfb   Peter M. Groen   Fixed paths
13
  		<< osdev::components::socket-cpp::SOCKPP_VERSION << '\n' << endl;
48b4c725   Peter M. Groen   Setting up Socket-pp
14
15
16
17
  
  	string host = (argc > 1) ? argv[1] : "localhost";
  	in_port_t port = (argc > 2) ? atoi(argv[2]) : 12345;
  
18a2dbfb   Peter M. Groen   Fixed paths
18
  	osdev::components::socket-cpp::socket_initializer sockInit;
48b4c725   Peter M. Groen   Setting up Socket-pp
19
  
18a2dbfb   Peter M. Groen   Fixed paths
20
  	osdev::components::socket-cpp::udp_socket sock;
48b4c725   Peter M. Groen   Setting up Socket-pp
21
  
18a2dbfb   Peter M. Groen   Fixed paths
22
  	if (!sock.connect(osdev::components::socket-cpp::inet_address(host, port))) {
48b4c725   Peter M. Groen   Setting up Socket-pp
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
  		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;
  }