-
Notifications
You must be signed in to change notification settings - Fork 5
/
UdpSocket.cpp
55 lines (44 loc) · 1.42 KB
/
UdpSocket.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
/********************************************************* {COPYRIGHT-TOP} ***
* Copyright 2016 IBM Corporation
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the MIT License
* which accompanies this distribution, and is available at
* http://opensource.org/licenses/MIT
********************************************************** {COPYRIGHT-END} **/
#include "UdpSocket.hpp"
#include <boost/locale.hpp>
using boost::asio::ip::udp;
using boost::locale::conv::utf_to_utf;
namespace {
/*
* This is apparently the safest UDP packet size, suitable for transmission
* across the internet. I suspect it's overkill and can be increased.
*/
const size_t UDP_MAX_PACKET_SIZE = 508;
}
UdpSocket::UdpSocket(const std::u16string& hostname, const std::u16string& port)
: iHostname(hostname),
iPort(port),
iSocket(iIOService) {
udp::resolver resolver(iIOService);
udp::resolver::query query(udp::v4(), utf_to_utf<char>(hostname), utf_to_utf<char>(port));
iEndpoint = *resolver.resolve(query);
iSocket.open(udp::v4());
}
UdpSocket::~UdpSocket() {
}
void UdpSocket::send(const std::string& data)
{
if ((iBuffer.length() + 1 + data.length()) > UDP_MAX_PACKET_SIZE) {
flush();
}
if (!iBuffer.empty()) {
iBuffer += u'\n';
}
iBuffer += data;
}
void UdpSocket::flush() {
iSocket.send_to(boost::asio::buffer(iBuffer), iEndpoint);
iBuffer.clear();
}