1 #ifndef EASYWSCLIENT_HPP_20120819_MIOFVASDTNUASZDQPLFD 2 #define EASYWSCLIENT_HPP_20120819_MIOFVASDTNUASZDQPLFD 3 4 // This code comes from: 5 // https://github.com/dhbaird/easywsclient 6 // 7 // To get the latest version: 8 // wget https://raw.github.com/dhbaird/easywsclient/master/easywsclient.hpp 9 // wget https://raw.github.com/dhbaird/easywsclient/master/easywsclient.cpp 10 11 #include <string> 12 #include <vector> 13 14 namespace easywsclient { 15 16 struct Callback_Imp { virtual void operator()(const std::string& message) = 0; }; 17 struct BytesCallback_Imp { virtual void operator()(const std::vector<uint8_t>& message) = 0; }; 18 19 class WebSocket { 20 public: 21 typedef WebSocket * pointer; 22 typedef enum readyStateValues { CLOSING, CLOSED, CONNECTING, OPEN } readyStateValues; 23 24 // Factories: 25 static pointer create_dummy(); 26 static pointer from_url(const std::string& url, const std::string& origin = std::string()); 27 static pointer from_url_no_mask(const std::string& url, const std::string& origin = std::string()); 28 29 // Interfaces: ~WebSocket()30 virtual ~WebSocket() { } 31 virtual void poll(int timeout = 0) = 0; // timeout in milliseconds 32 virtual void send(const std::string& message) = 0; 33 virtual void sendBinary(const std::string& message) = 0; 34 virtual void sendBinary(const std::vector<uint8_t>& message) = 0; 35 virtual void sendPing() = 0; 36 virtual void close() = 0; 37 virtual readyStateValues getReadyState() const = 0; 38 39 template<class Callable> dispatch(Callable callable)40 void dispatch(Callable callable) 41 // For callbacks that accept a string argument. 42 { // N.B. this is compatible with both C++11 lambdas, functors and C function pointers 43 struct _Callback : public Callback_Imp { 44 Callable& callable; 45 _Callback(Callable& callable) : callable(callable) { } 46 void operator()(const std::string& message) { callable(message); } 47 }; 48 _Callback callback(callable); 49 _dispatch(callback); 50 } 51 52 template<class Callable> dispatchBinary(Callable callable)53 void dispatchBinary(Callable callable) 54 // For callbacks that accept a std::vector<uint8_t> argument. 55 { // N.B. this is compatible with both C++11 lambdas, functors and C function pointers 56 struct _Callback : public BytesCallback_Imp { 57 Callable& callable; 58 _Callback(Callable& callable) : callable(callable) { } 59 void operator()(const std::vector<uint8_t>& message) { callable(message); } 60 }; 61 _Callback callback(callable); 62 _dispatchBinary(callback); 63 } 64 65 protected: 66 virtual void _dispatch(Callback_Imp& callable) = 0; 67 virtual void _dispatchBinary(BytesCallback_Imp& callable) = 0; 68 }; 69 70 } // namespace easywsclient 71 72 #endif /* EASYWSCLIENT_HPP_20120819_MIOFVASDTNUASZDQPLFD */ 73