blob: 52b62a5039390975a0a507d42c7603955a8532a7 [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>
Jeff Thompsonb9e3c8e2013-08-02 11:42:51 -07007#include "../face.hpp"
Jeff Thompsonbc53c522013-07-17 17:11:48 -07008#include "../c/util/ndn_realloc.h"
9#include "UdpTransport.hpp"
10
11using namespace std;
12
13namespace ndn {
14
Jeff Thompsonb9e3c8e2013-08-02 11:42:51 -070015void UdpTransport::connect(Face &face)
Jeff Thompsonbc53c522013-07-17 17:11:48 -070016{
17 ndn_Error error;
Jeff Thompsonb9e3c8e2013-08-02 11:42:51 -070018 if (error = ndn_UdpTransport_connect(&transport_, (char *)face.getHost(), face.getPort()))
Jeff Thompsonbc53c522013-07-17 17:11:48 -070019 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 *)
Jeff Thompsonf0fea002013-07-30 17:22:42 -070024 ndn_BinaryXmlElementReader_init
Jeff Thompsonb9e3c8e2013-08-02 11:42:51 -070025 (&elementReader_, &face, (unsigned char *)malloc(initialLength), initialLength, ndn_realloc);
Jeff Thompsonbc53c522013-07-17 17:11:48 -070026
27 // TODO: Properly indicate connected status.
Jeff Thompsonb9e3c8e2013-08-02 11:42:51 -070028 face_ = &face;
Jeff Thompsonbc53c522013-07-17 17:11:48 -070029}
30
Jeff Thompson60eaae32013-07-30 15:46:19 -070031void UdpTransport::send(const unsigned char *data, unsigned int dataLength)
Jeff Thompsonbc53c522013-07-17 17:11:48 -070032{
33 ndn_Error error;
Jeff Thompson60eaae32013-07-30 15:46:19 -070034 if (error = ndn_UdpTransport_send(&transport_, (unsigned char *)data, dataLength))
Jeff Thompsonbc53c522013-07-17 17:11:48 -070035 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
Jeff Thompsonf0fea002013-07-30 17:22:42 -070047 ndn_BinaryXmlElementReader_onReceivedData(&elementReader_, buffer, nBytes);
Jeff Thompsonbc53c522013-07-17 17:11:48 -070048 } 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}