Subversion Repositories HomeAutomation

Rev

Details | Last modification | View Log | SVN | RSS feed

Rev Author Line No. Line
1309 runge 1
/*
2
 * UdpConnection.h
3
 *
4
 *  Created on: Jul 17, 2009
5
 *      Author: Mattias Runge
6
 */
7
 
8
#ifndef UDPCONNECTION_H_
9
#define UDPCONNECTION_H_
10
 
11
#include <string>
12
#include "BitBuffer.h"
13
#include "Logger.h"
14
#include <boost/array.hpp>
15
#include <boost/asio.hpp>
16
#include "../utils/Thread.h"
17
#include <boost/signal.hpp>
18
 
19
namespace atom {
20
namespace utils {
21
 
22
using boost::asio::ip::udp;
23
using namespace std;
24
 
25
class UdpServer
26
{
27
public:
28
    UdpConnection(unsigned int port)
29
    : socket(this->ioService, udp::endpoint(udp::v4(), port))
30
    {
31
        this->socket.async_receive_from(
32
                boost::asio::buffer(data_, max_length), sender_endpoint_,
33
                boost::bind(&server::handle_receive_from, this,
34
                        boost::asio::placeholders::error,
35
                        boost::asio::placeholders::bytes_transferred));
36
 
37
    }
38
 
39
private:
40
 
41
    void
42
    handleReceive(const boost::system::error_code& error, std::size_t /*bytes_transferred*/)
43
    {
44
        if (!error || error == boost::asio::error::message_size)
45
        {
46
            boost::shared_ptr<std::string>
47
                    message(new std::string(make_daytime_string()));
48
 
49
            socket_.async_send_to(boost::asio::buffer(*message), remote_endpoint_, boost::bind(&udp_server::handle_send, this, message, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
50
 
51
            start_receive();
52
        }
53
    }
54
 
55
    void
56
    handle_send(boost::shared_ptr<std::string> /*message*/, const boost::system::error_code& /*error*/, std::size_t /*bytes_transferred*/)
57
    {
58
    }
59
 
60
    udp::socket socket;
61
    udp::endpoint remoteEndpoint;
62
    boost::array<char, 1> receiveBuffer;
63
 
64
    io_service ioService;
65
};
66
 
67
class UdpConnection
68
{
69
    typedef boost::signal<void
70
    (BitBuffer &buffer)> OnIncommingSignal;
71
 
72
public:
73
    UdpConnection(string ip, unsigned int port);
74
    virtual
75
    ~UdpConnection();
76
 
77
    void
78
    connect();
79
    void
80
    disconnect();
81
    void
82
    write(BitBuffer buffer);
83
 
84
protected:
85
    string _ip;
86
    unsigned int _port;
87
    udp::socket *_outSocket;
88
    udp::socket *_inSocket;
89
    udp::endpoint _receiverEndpoint;
90
 
91
private:
92
    Logger LOG;
93
};
94
 
95
}
96
}
97
 
98
#endif /* UDPCONNECTION_H_ */