SockIt
|
00001 /* 00002 * UdpEvent.cpp 00003 * 00004 * This object is passed as an argument to a Javascript callback when an object gets a message. It enables the 00005 * Javascript to send a reply. 00006 */ 00007 00008 #include "UdpEvent.h" 00009 00010 UdpEvent::UdpEvent(Udp * udp_object, boost::shared_ptr<udp::socket> socket, boost::shared_ptr<udp::endpoint> endpoint, string data) : 00011 port(-1), socket(socket), endpoint(endpoint), udp_object(udp_object), failed(false), data(data) 00012 { 00013 // Check to see if any the parameters are null, and log and fail if this occurs 00014 if (endpoint && udp_object) 00015 { 00016 // Initialize only if it's safe 00017 host = boost::lexical_cast<string>(endpoint->address()); 00018 port = endpoint->port(); 00019 } 00020 else 00021 { 00022 // Fail permanently and log it 00023 failed = true; 00024 00025 string message("UDP Event was not properly initialized, permanently failed."); 00026 Logger::error(message, port, host); 00027 fire_error(message); 00028 } 00029 } 00030 00031 UdpEvent::~UdpEvent() 00032 { 00033 // do not free socket, endpoint or udp here 00034 } 00035 00036 void UdpEvent::send_bytes(const vector<byte> & bytes) 00037 { 00038 string data; 00039 00040 for (int i = 0; i < bytes.size(); i++) 00041 { 00042 data.push_back((unsigned char) bytes[i]); 00043 } 00044 00045 send(data); 00046 } 00047 00048 void UdpEvent::send(const string & data) 00049 { 00050 // Don't send if we've permanently failed 00051 if (failed) 00052 { 00053 string message("UDP event failed to send, Event already failed permanently"); 00054 Logger::error(message, port, host); 00055 fire_error(message); 00056 return; 00057 } 00058 00059 if (udp_object && udp_object->failed) 00060 { 00061 // Log & fire an error 00062 string message("UDP event failed trying to reply to a UDP object that has permanently failed!"); 00063 Logger::error(message, port, host); 00064 fire_error(message); 00065 return; 00066 } 00067 00068 if (socket && endpoint) 00069 { 00070 udp_object->pending_sends++; 00071 socket->async_send_to(boost::asio::buffer(data.data(), data.size()), *endpoint, 00072 boost::bind(&Udp::send_handler, udp_object, _1, _2, data, host, endpoint->port())); 00073 } 00074 } 00075 00076 string UdpEvent::read() const 00077 { 00078 return data; 00079 } 00080 00081 FB::VariantList UdpEvent::read_bytes() const 00082 { 00083 FB::VariantList fb_bytes; 00084 00085 for (int i = 0; i < data.size(); i++) 00086 { 00087 fb_bytes.push_back((unsigned char) (data.data())[i]); 00088 } 00089 00090 return fb_bytes; 00091 } 00092 00093 string UdpEvent::get_host(void) 00094 { 00095 return host; 00096 } 00097 00098 unsigned short UdpEvent::get_port(void) 00099 { 00100 return port; 00101 }