Jeff Thompson | fcf347d | 2013-07-15 11:30:44 -0700 | [diff] [blame] | 1 | /** |
| 2 | * @author: Jeff Thompson |
| 3 | * See COPYING for copyright and distribution information. |
| 4 | */ |
| 5 | |
| 6 | #include <stdexcept> |
Jeff Thompson | 0cb7aee | 2013-07-16 16:18:06 -0700 | [diff] [blame] | 7 | #include "../NDN.hpp" |
| 8 | #include "../c/encoding/BinaryXMLElementReader.h" |
Jeff Thompson | fcf347d | 2013-07-15 11:30:44 -0700 | [diff] [blame] | 9 | #include "TcpTransport.hpp" |
| 10 | |
| 11 | using namespace std; |
| 12 | |
| 13 | namespace ndn { |
| 14 | |
Jeff Thompson | 0cb7aee | 2013-07-16 16:18:06 -0700 | [diff] [blame] | 15 | void TcpTransport::connect(NDN &ndn) |
Jeff Thompson | fcf347d | 2013-07-15 11:30:44 -0700 | [diff] [blame] | 16 | { |
| 17 | ndn_Error error; |
Jeff Thompson | 0cb7aee | 2013-07-16 16:18:06 -0700 | [diff] [blame] | 18 | if (error = ndn_TcpTransport_connect(&transport_, (char *)ndn.getHost(), ndn.getPort())) |
| 19 | throw std::runtime_error(ndn_getErrorString(error)); |
| 20 | |
| 21 | // TODO: Properly indicate connected status. |
| 22 | ndn_ = &ndn; |
Jeff Thompson | fcf347d | 2013-07-15 11:30:44 -0700 | [diff] [blame] | 23 | } |
| 24 | |
| 25 | void TcpTransport::send(unsigned char *data, unsigned int dataLength) |
| 26 | { |
| 27 | ndn_Error error; |
| 28 | if (error = ndn_TcpTransport_send(&transport_, data, dataLength)) |
| 29 | throw std::runtime_error(ndn_getErrorString(error)); |
| 30 | } |
| 31 | |
Jeff Thompson | 0cb7aee | 2013-07-16 16:18:06 -0700 | [diff] [blame] | 32 | void TcpTransport::tempReceive() |
Jeff Thompson | fcf347d | 2013-07-15 11:30:44 -0700 | [diff] [blame] | 33 | { |
Jeff Thompson | 0cb7aee | 2013-07-16 16:18:06 -0700 | [diff] [blame] | 34 | if (!ndn_) |
| 35 | // TODO: Properly check if connected. |
| 36 | return; |
Jeff Thompson | 7ed97c7 | 2013-07-16 17:56:41 -0700 | [diff] [blame^] | 37 | |
| 38 | try { |
| 39 | ndn_BinaryXMLElementReader elementReader; |
| 40 | // Automatically cast ndn_ to (struct ndn_ElementListener *) |
| 41 | ndn_BinaryXMLElementReader_init(&elementReader, ndn_); |
Jeff Thompson | 0cb7aee | 2013-07-16 16:18:06 -0700 | [diff] [blame] | 42 | |
Jeff Thompson | 7ed97c7 | 2013-07-16 17:56:41 -0700 | [diff] [blame^] | 43 | ndn_Error error; |
| 44 | unsigned char buffer[8000]; |
| 45 | unsigned int nBytes; |
| 46 | if (error = ndn_TcpTransport_receive(&transport_, buffer, sizeof(buffer), &nBytes)) |
| 47 | throw std::runtime_error(ndn_getErrorString(error)); |
| 48 | |
| 49 | ndn_BinaryXMLElementReader_onReceivedData(&elementReader, buffer, nBytes); |
| 50 | } catch (...) { |
| 51 | // This function is called by the socket callback, so don't send an exception back to it. |
| 52 | // TODO: Log the exception? |
| 53 | } |
Jeff Thompson | fcf347d | 2013-07-15 11:30:44 -0700 | [diff] [blame] | 54 | } |
| 55 | |
| 56 | } |