blob: ae0124f0815a44ec3faaa1b4b58cbf76461e9f51 [file] [log] [blame]
Jeff Thompsonbc53c522013-07-17 17:11:48 -07001/**
2 * @author: Jeff Thompson
3 * See COPYING for copyright and distribution information.
4 */
5
6#include <stdexcept>
7#include "../NDN.hpp"
8#include "../c/util/ndn_realloc.h"
9#include "UdpTransport.hpp"
10
11using namespace std;
12
13namespace ndn {
14
15void UdpTransport::connect(NDN &ndn)
16{
17 ndn_Error error;
18 if (error = ndn_UdpTransport_connect(&transport_, (char *)ndn.getHost(), ndn.getPort()))
19 throw std::runtime_error(ndn_getErrorString(error));
20
21 // TODO: This belongs in the socket listener.
22 const unsigned int initialLength = 1000;
23 // Automatically cast ndn_ to (struct ndn_ElementListener *)
24 ndn_BinaryXMLElementReader_init
25 (&elementReader_, &ndn, (unsigned char *)malloc(initialLength), initialLength, ndn_realloc);
26
27 // TODO: Properly indicate connected status.
28 ndn_ = &ndn;
29}
30
31void UdpTransport::send(unsigned char *data, unsigned int dataLength)
32{
33 ndn_Error error;
34 if (error = ndn_UdpTransport_send(&transport_, data, dataLength))
35 throw std::runtime_error(ndn_getErrorString(error));
36}
37
38void UdpTransport::tempReceive()
39{
40 try {
41 ndn_Error error;
42 unsigned char buffer[8000];
43 unsigned int nBytes;
44 if (error = ndn_UdpTransport_receive(&transport_, buffer, sizeof(buffer), &nBytes))
45 throw std::runtime_error(ndn_getErrorString(error));
46
47 ndn_BinaryXMLElementReader_onReceivedData(&elementReader_, buffer, nBytes);
48 } catch (...) {
49 // This function is called by the socket callback, so don't send an exception back to it.
50 // TODO: Log the exception?
51 }
52}
53
54}