-
Notifications
You must be signed in to change notification settings - Fork 0
/
udpserver.cpp
79 lines (65 loc) · 1.73 KB
/
udpserver.cpp
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
* Derived from example of Christopher M. Kohlhoff
*
* /
#include <ctime>
#include <iostream>
#include <string>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::udp;
class udp_server
{
public:
udp_server(boost::asio::io_service& io_service, int port)
: socket_(io_service, udp::endpoint(udp::v4(), port))
{
std::cout << "Listening on port " << port << std::endl;
start_receive();
}
private:
void start_receive()
{
socket_.async_receive_from(
boost::asio::buffer(recv_buffer_), remote_endpoint_,
boost::bind(&udp_server::handle_receive, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
std::cout << "Bytes received: " << boost::asio::placeholders::bytes_transferred << std::endl;
std::cout << "Received: " << std::string(reinterpret_cast<const char*>(recv_buffer_.data())) << std::endl;
}
void handle_receive(const boost::system::error_code& error,
std::size_t bytes_transferred)
{
if (!error || error == boost::asio::error::message_size)
{
start_receive();
}
}
udp::socket socket_;
udp::endpoint remote_endpoint_;
boost::array<char, 1000> recv_buffer_;
};
int main(int argc, char** argv)
{
if (argc < 2) {
std::cout << "Usage: udpserver [listen port]\n";
std::cout << "Example: udpserver 8094\n";
return 1;
}
unsigned int port = atoi(argv[1]);
setvbuf(stdout, NULL, _IONBF, 0);
try
{
boost::asio::io_service io_service;
udp_server server(io_service, port);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}