blob: 69a98696971489abb846ddaf7019dfb10a8eb4e9 [file] [log] [blame]
Jeff Thompsonfcf347d2013-07-15 11:30:44 -07001/**
2 * @author: Jeff Thompson
3 * See COPYING for copyright and distribution information.
4 */
5
6#include <stdexcept>
Jeff Thompson0cb7aee2013-07-16 16:18:06 -07007#include "../NDN.hpp"
Jeff Thompson5e275b42013-07-16 19:10:11 -07008#include "../c/util/ndn_realloc.h"
Jeff Thompsonfcf347d2013-07-15 11:30:44 -07009#include "TcpTransport.hpp"
10
11using namespace std;
12
13namespace ndn {
14
Jeff Thompson0cb7aee2013-07-16 16:18:06 -070015void TcpTransport::connect(NDN &ndn)
Jeff Thompsonfcf347d2013-07-15 11:30:44 -070016{
17 ndn_Error error;
Jeff Thompson0cb7aee2013-07-16 16:18:06 -070018 if (error = ndn_TcpTransport_connect(&transport_, (char *)ndn.getHost(), ndn.getPort()))
19 throw std::runtime_error(ndn_getErrorString(error));
Jeff Thompsonb002f902013-07-16 18:07:18 -070020
21 // TODO: This belongs in the socket listener.
Jeff Thompson5e275b42013-07-16 19:10:11 -070022 const unsigned int initialLength = 1000;
Jeff Thompsonb002f902013-07-16 18:07:18 -070023 // Automatically cast ndn_ to (struct ndn_ElementListener *)
Jeff Thompson5e275b42013-07-16 19:10:11 -070024 ndn_BinaryXMLElementReader_init
25 (&elementReader_, &ndn, (unsigned char *)malloc(initialLength), initialLength, ndn_realloc);
Jeff Thompson0cb7aee2013-07-16 16:18:06 -070026
27 // TODO: Properly indicate connected status.
28 ndn_ = &ndn;
Jeff Thompsonfcf347d2013-07-15 11:30:44 -070029}
30
Jeff Thompsonb605b5d2013-07-30 15:12:56 -070031void TcpTransport::send(const unsigned char *data, unsigned int dataLength)
Jeff Thompsonfcf347d2013-07-15 11:30:44 -070032{
33 ndn_Error error;
34 if (error = ndn_TcpTransport_send(&transport_, data, dataLength))
35 throw std::runtime_error(ndn_getErrorString(error));
36}
37
Jeff Thompson0cb7aee2013-07-16 16:18:06 -070038void TcpTransport::tempReceive()
Jeff Thompsonfcf347d2013-07-15 11:30:44 -070039{
Jeff Thompsonb002f902013-07-16 18:07:18 -070040 try {
Jeff Thompson7ed97c72013-07-16 17:56:41 -070041 ndn_Error error;
42 unsigned char buffer[8000];
43 unsigned int nBytes;
44 if (error = ndn_TcpTransport_receive(&transport_, buffer, sizeof(buffer), &nBytes))
45 throw std::runtime_error(ndn_getErrorString(error));
46
Jeff Thompsonb002f902013-07-16 18:07:18 -070047 ndn_BinaryXMLElementReader_onReceivedData(&elementReader_, buffer, nBytes);
Jeff Thompson7ed97c72013-07-16 17:56:41 -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 }
Jeff Thompsonfcf347d2013-07-15 11:30:44 -070052}
53
54}