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