websocket_connection.cpp
Go to the documentation of this file.
00001 #include <boost/bind.hpp>
00002 #include <boost/make_shared.hpp>
00003 #include <limits>
00004 #include "async_web_server_cpp/websocket_connection.hpp"
00005 
00006 namespace async_web_server_cpp
00007 {
00008 
00009 WebsocketConnection::WebsocketConnection(HttpConnectionPtr connection)
00010   : connection_(connection) {}
00011 
00012 void WebsocketConnection::set_message_handler(MessageHandler& handler)
00013 {
00014   handler_ = handler;
00015 }
00016 
00017 bool WebsocketConnection::sendTextMessage(const std::string& content)
00018 {
00019   async_web_server_cpp::WebsocketMessage m;
00020   m.type = async_web_server_cpp::WebsocketMessage::type_text;
00021   m.content = content;
00022   return sendMessage(m);
00023 }
00024 bool WebsocketConnection::sendPingMessage(const std::string& content)
00025 {
00026   async_web_server_cpp::WebsocketMessage m;
00027   m.type = async_web_server_cpp::WebsocketMessage::type_ping;
00028   m.content = content;
00029   return sendMessage(m);
00030 }
00031 
00032 
00033 bool WebsocketConnection::sendMessage(const WebsocketMessage& message)
00034 {
00035   WebsocketFrame frame;
00036   if (frame.fromMessage(message))
00037   {
00038     return sendFrame(frame);
00039   }
00040   return false;
00041 }
00042 
00043 bool WebsocketConnection::sendFrame(WebsocketFrame& frame)
00044 {
00045   std::vector<unsigned char> buffer;
00046   if (frame.serialize(buffer))
00047   {
00048     connection_->write_and_clear(buffer);
00049     return true;
00050   }
00051   return false;
00052 }
00053 
00054 
00055 void WebsocketConnection::static_handle_read(WebsocketConnectionWeakPtr weak_this, const char* begin, const char* end)
00056 {
00057   WebsocketConnectionPtr _this = weak_this.lock();
00058   if (_this)
00059     _this->handle_read(begin, end);
00060 }
00061 void WebsocketConnection::handle_read(const char* begin, const char* end)
00062 {
00063   boost::tribool frame_result;
00064   const char* parse_end = begin;
00065   while (parse_end < end)
00066   {
00067     boost::tie(frame_result, parse_end) = frame_parser_.parse(frame_, parse_end, end);
00068     if (frame_result)
00069     {
00070       frame_parser_.reset();
00071       boost::tribool message_result = frame_buffer_.consume(message_, frame_);
00072 
00073       if (message_result)
00074       {
00075         if (handler_)
00076           handler_(message_);
00077       }
00078     }
00079     else if (!frame_result)
00080     {
00081       frame_parser_.reset();
00082       message_.type = WebsocketMessage::type_unknown;
00083     }
00084   }
00085   WebsocketConnectionWeakPtr this_weak(shared_from_this());
00086   connection_->async_read(boost::bind(&WebsocketConnection::static_handle_read, this_weak, _1, _2));
00087 }
00088 
00089 }


async_web_server_cpp
Author(s): Mitchell Wills
autogenerated on Fri Mar 4 2016 11:30:14