blob: 603f5e3100a1eb43cfce62f705c121dc0c0e343b [file] [log] [blame]
Alexander Afanasyevfe3b1502013-12-18 16:45:03 -08001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
2/**
3 * Copyright (C) 2013 Regents of the University of California.
4 * @author: Jeff Thompson <jefft0@remap.ucla.edu>
5 * See COPYING for copyright and distribution information.
6 */
7
8#include <stdexcept>
9#include <stdlib.h>
10
11#include <ndn-cpp/face.hpp>
12#include <ndn-cpp/transport/unix-transport.hpp>
13
14#include <boost/asio.hpp>
15#include <boost/bind.hpp>
16
17using namespace std;
18typedef boost::asio::local::datagram_protocol protocol;
19
20namespace ndn {
21
22const size_t MAX_LENGTH = 9000;
23
24class UnixTransport::Impl
25{
26public:
27 Impl() : socket_(io_)
28 {
29 }
30
31 bool
32 connect(const std::string &unixSocket, ElementListener& elementListener)
33 {
34 socket_.open();
35 socket_.connect(protocol::endpoint(unixSocket));
36 // socket_.async_connect(protocol::endpoint(unixSocket));
37
38 socket_.async_receive(boost::asio::buffer(inputBuffer_, MAX_LENGTH), 0,
39 boost::bind(&Impl::handle_async_receive, this, _1, _2));
40
41 return true;
42 }
43
44 void
45 send(const uint8_t *data, size_t dataLength)
46 {
47 socket_.send(boost::asio::buffer(data, dataLength));
48 }
49
50 void
51 processEvents()
52 {
53 io_.poll();
54 // from boost docs:
55 // The poll() function runs handlers that are ready to run, without blocking, until the io_service has been stopped or there are no more ready handlers.
56 }
57
58 void
59 handle_async_receive(const boost::system::error_code& error, std::size_t bytes_recvd)
60 {
61 if (!error && bytes_recvd > 0)
62 {
63 // inputBuffer_ has bytes_recvd received bytes of data
64 }
65
66 socket_.async_receive(boost::asio::buffer(inputBuffer_, MAX_LENGTH), 0,
67 boost::bind(&Impl::handle_async_receive, this, _1, _2));
68 }
69
70 void
71 close()
72 {
73 socket_.close();
74 }
75
76private:
77 boost::asio::io_service io_;
78
79 protocol::socket socket_;
80
81 uint8_t inputBuffer_[MAX_LENGTH];
82};
83
84UnixTransport::UnixTransport(const std::string &unixSocket/* = "/tmp/.ndnd.sock"*/)
85 : unixSocket_(unixSocket)
86 , isConnected_(false)
87 , impl_(new UnixTransport::Impl())
88{
89}
90
91UnixTransport::~UnixTransport()
92{
93}
94
95void
96UnixTransport::connect(ElementListener& elementListener)
97{
98 if (impl_->connect(unixSocket_, elementListener))
99 {
100 isConnected_ = true;
101 }
102}
103
104void
105UnixTransport::send(const uint8_t *data, size_t dataLength)
106{
107 impl_->send(data, dataLength);
108}
109
110void
111UnixTransport::processEvents()
112{
113 impl_->processEvents();
114}
115
116bool
117UnixTransport::getIsConnected()
118{
119 return isConnected_;
120}
121
122void
123UnixTransport::close()
124{
125 impl_->close();
126}
127
128}