blob: 1db18bbc14ff52c2ffd54cb7e27c12d19b755acc [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"
8#include "../c/encoding/BinaryXMLElementReader.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));
20
21 // TODO: Properly indicate connected status.
22 ndn_ = &ndn;
Jeff Thompsonfcf347d2013-07-15 11:30:44 -070023}
24
25void 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 Thompson0cb7aee2013-07-16 16:18:06 -070032void TcpTransport::tempReceive()
Jeff Thompsonfcf347d2013-07-15 11:30:44 -070033{
Jeff Thompson0cb7aee2013-07-16 16:18:06 -070034 if (!ndn_)
35 // TODO: Properly check if connected.
36 return;
Jeff Thompson7ed97c72013-07-16 17:56:41 -070037
38 try {
39 ndn_BinaryXMLElementReader elementReader;
40 // Automatically cast ndn_ to (struct ndn_ElementListener *)
41 ndn_BinaryXMLElementReader_init(&elementReader, ndn_);
Jeff Thompson0cb7aee2013-07-16 16:18:06 -070042
Jeff Thompson7ed97c72013-07-16 17:56:41 -070043 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 Thompsonfcf347d2013-07-15 11:30:44 -070054}
55
56}