1 #ifndef _spin_udpsocket_h
2 #define _spin_udpsocket_h
4 #include "Details/prologue.h"
5 #include <boost/enable_shared_from_this.hpp>
6 #include <boost/function.hpp>
7 #include <boost/tuple/tuple.hpp>
8 #include <boost/thread/recursive_mutex.hpp>
9 #include <Acari/Attributes.h>
10 #include "Details/Address.h"
22 class SPIN_API UDPSocket
: public boost::enable_shared_from_this
< UDPSocket
>, private Acari::Attributes
25 //! Type of the call-back called when errors occur
26 typedef boost::function
< void() > OnErrorCallback
;
27 //! Possible status flags
30 //! All is well - no errors occur
32 //! An error occurred during communication
34 //! Communications are done on this connection - the connection is closed
38 using Acari::Attributes::getAttribute
;
39 using Acari::Attributes::allocateAttribute
;
41 UDPSocket(const Details::Address
& address
= Details::Address(0), unsigned short port
= 0);
44 std::size_t send(const Details::Address
& to
, unsigned short port
, const std::vector
< char > & data
);
45 std::size_t send(const Details::Address
& to
, unsigned short port
, const std::string
& data
) { return send(to
, port
, std::vector
< char >(data
.begin(), data
.end())); }
46 std::size_t send(const Details::Address
& to
, unsigned short port
, const char * data
) { return send(to
, port
, std::string(data
)); }
47 template < typename T
>
48 std::size_t send(const Details::Address
& to
, unsigned short port
, const T
& data
) { return send(to
, port
, serialize(data
)); }
50 boost::tuple
< Details::Address
, unsigned short, std::size_t > recv(std::vector
< char > & buffer
, unsigned long timeout
= ~0);
51 boost::tuple
< Details::Address
, unsigned short, std::size_t > peek(std::vector
< char > & buffer
, unsigned long timeout
= ~0);
53 void clearPeekBuffer();
58 /** Set a new data handler, which will be called whenever data is ready on the connection.
59 * This allows for asynchronous handling of new data. Behind the scenes, a separate thread
60 * will use select(2) on the connection to wait for data. */
61 void setDataHandler(Handlers::UDPDataHandler
& handler
, OnErrorCallback on_error_callback
= OnErrorCallback());
62 //! Clear the new-data handler, returning to a synchronous mode of operation
63 void clearDataHandler();
65 //! Get the status of this connection
66 int getStatus() const { return status_
; }
69 UDPSocket(const UDPSocket
&);
70 UDPSocket
& operator=(const UDPSocket
&);
72 void checkStatus(const char * for_whom
) const;
76 mutable boost::recursive_mutex fd_lock_
;
78 Handlers::UDPDataHandler
* data_handler_
;
79 boost::recursive_mutex peek_buffer_lock_
;
80 boost::tuple
< Details::Address
, unsigned short, std::size_t, std::vector
< char > > peek_buffer_
;