bool OTSocket::Send(const std::string & str_Reply)
{
	OT_ASSERT_MSG(NULL != m_pSocket, "m_pSocket == NULL in OTSocket::Send()");
	OT_ASSERT_MSG(NULL != m_pContext, "m_pContext == NULL in OTSocket::Send()");
	OT_ASSERT_MSG(str_Reply.size() > 0, "str_Reply.size() > 0");
	// -----------------------------------
	const long lLatencySendMilliSec	= OTLog::GetLatencySendMs();
	const long lLatencySendMicroSec	= lLatencySendMilliSec*1000; // Microsecond is 1000 times smaller than millisecond.
	
	// Convert the std::string (reply) into a ZMQ message
	zmq::message_t reply (str_Reply.length());
	memcpy((void *) reply.data(), str_Reply.c_str(), str_Reply.length());
	// -----------------------------------
	
	bool bSuccessSending	= false;
	
	if (OTLog::IsBlocking())
	{
		bSuccessSending = m_pSocket->send(reply); // Blocking.
	}
	else // not blocking
	{
		int		nSendTries	= OTLog::GetLatencySendNoTries();
		long	lDoubling	= lLatencySendMicroSec;		
		bool	bKeepTrying = true;
		
		while (bKeepTrying && (nSendTries > 0))
		{
			zmq::pollitem_t items [] = {
				{ (*m_pSocket), 0, ZMQ_POLLOUT,	0 }
			};
			
			const int nPoll = zmq::poll(&items[0], 1, lDoubling);	// ZMQ_POLLOUT, 1 item, timeout (microseconds in ZMQ 2.1; changes to milliseconds in 3.0)					
			lDoubling *= 2;
			
			if (items[0].revents & ZMQ_POLLOUT)
			{
				bSuccessSending = m_pSocket->send(reply, ZMQ_NOBLOCK); // <=========== SEND ===============
				OTLog::SleepMilliseconds( 1 );
				
				if (!bSuccessSending)
				{
					if (false == HandleSendingError())
						bKeepTrying = false;
				}
				else
					break; // (Success -- we're done in this loop.)
			}
			else if ((-1) == nPoll) // error.
			{
				if (false == HandlePollingError())
					bKeepTrying = false;
			}
			
			--nSendTries;
		}
	}
	
	return bSuccessSending;
}
示例#2
0
void
raw_sender(zmq::socket_t& s)
{
  for (size_t i = 0; i < ITERS; ++i)
  {
    zmq::message_t msg1(ARRAY_LEN(PART1)-1);
    memcpy(msg1.data(), PART1, msg1.size());
    s.send(msg1, ZMQ_SNDMORE);

    zmq::message_t msg2(ARRAY_LEN(PART2)-1);
    memcpy(msg2.data(), PART2, msg2.size());
    s.send(msg2, ZMQ_SNDMORE);

    zmq::message_t msg3(ARRAY_LEN(PART3)-1);
    memcpy(msg3.data(), PART3, msg3.size());
    s.send(msg3);

    zmq::message_t msg_res;
    s.recv(&msg_res, 0);

    if (i % 1000 == 0)
    {
      std::cout << ".";
      std::cout.flush();
    }
  }
}
示例#3
0
static bool
s_send (zmq::socket_t & socket, const char* buffer, unsigned length, bool zerocopy=false) {
    if(zerocopy) {
         zmq::message_t message((void *)buffer, length, NULL, NULL);
        return socket.send (message);
    }else {
        zmq::message_t message(length);
        memcpy (message.data(),buffer, length);
        return socket.send (message);
    }    
}
示例#4
0
//  Convert string to 0MQ string and send to socket
static bool
s_send (zmq::socket_t & socket, const std::string & string, bool zerocopy=false) {
    if(zerocopy) {
        zmq::message_t message((void *)string.data(), string.size(), NULL, NULL);
        return socket.send (message);
    }else {
        zmq::message_t message(string.size());
        memcpy (message.data(),string.data(), string.size());
        return socket.send (message);
    }

}
示例#5
0
void MessageSender::rawSocketSend( zmq::socket_t& a_socket, const std::string& a_name, const unsigned char* a_msg, size_t a_msgSize )
{
    bool ok = false;
    try
    {
        ok = a_socket.send( a_name.data(), a_name.size(), ZMQ_SNDMORE );
        ok = a_socket.send( a_msg, a_msgSize );
    }
    catch( const zmq::error_t& ex )
    {
        //std::cout << __PRETTY_FUNCTION__ << " " << ex.what() << std::endl;
    }
}
示例#6
0
//  Sends string as 0MQ string, as multipart non-terminal
static bool
s_sendmore (zmq::socket_t & socket, const std::string & string, bool zerocopy=false) {

    zmq::message_t *pmessage = NULL;
    if(zerocopy) {
        zmq::message_t  message ((void *)string.c_str(), string.length(), NULL, NULL);
        return socket.send (message, ZMQ_SNDMORE);
    }else {
       zmq::message_t message(string.size());
       memcpy (message.data(), string.data(), string.size());
       return socket.send (message, ZMQ_SNDMORE);
    }

}
示例#7
0
void safeSend(zmq::socket_t &sock, const char *buf, size_t buflen) {
	char tnam[100];
	int pgn_rc = pthread_getname_np(pthread_self(),tnam, 100);
	assert(pgn_rc == 0);

	//if (buflen>10){FileLogger fl(program_name); fl.f() << tnam << " sending " << buf << "\n"; }

	while (!MessagingInterface::aborted()) {
		try {
			zmq::message_t msg(buflen);
			memcpy(msg.data(), buf, buflen );
			sock.send(msg);
			break;
		}
		catch (zmq::error_t) {
			if (zmq_errno() != EINTR && zmq_errno() != EAGAIN) {
				{
					FileLogger fl(program_name); 
					fl.f()  << tnam << " safeSend error " << errno << " " << zmq_strerror(errno) << "\n";
				}
				if (zmq_errno() == EFSM) {
					usleep(1000);
					throw;
				}
				usleep(10);
				continue;
			} else {
				std::cerr << tnam << " safeSend error " << errno << " " << zmq_strerror(errno) << "\n";
				usleep(10);
			}
		}
	}
}
示例#8
0
void sendOverSocket(zmq::socket_t &socket, const message::Node &msg) {
  std::string msg_str;
  msg.SerializeToString(&msg_str);

  zmq::message_t request(msg_str.size());
  memcpy((void*)request.data(), msg_str.c_str(), msg_str.size());

  // Sometimes sending will fail with EINTR.  In this case, we try to
  // send the message again.
  while (true) {
    int failed_attempts = 0;
    try {
      bool sentOK = socket.send(request);
      // If sentOK is false, there was an EAGAIN.  We handle this the
      // same as EINTR.
      if (!sentOK) {
        failed_attempts++;
        if (failed_attempts > 10) abort();
        continue;
      }
      // Success: stop the loop.
      break;
    } catch (zmq::error_t &e) {
      failed_attempts++;
      if (failed_attempts > 10) abort();
      if (e.num() == EINTR) {
        continue;
      }
      // If it was something other than EINTR, rethrow the exception.
      throw e;
    }
  }
}
/**
 * Convert string to 0MQ string and send to socket.
 */
static bool s_send (zmq::socket_t& socket, const std::string& string) {
  zmq::message_t message (string.size());
  memcpy (message.data(), string.data(), string.size());

  bool rc = socket.send (message);
  return rc;
}
 void nag() {
   //are we waiting on the next files
   if(wait_until && wait_until < std::time(nullptr)) {
     socket.send(std::string("N"), ZMQ_DONTWAIT);
     wait_until = 0;
   }
 }
示例#11
0
void process_frontend(zmq::socket_t& frontend, int& available_workers) {
  zmq::message_t req;
  frontend.recv(&req);
  zmq::message_t reply(sizeof(available_workers));
  memcpy(reply.data(), &available_workers, sizeof(available_workers));
  frontend.send(reply);
}
示例#12
0
bool send (zmq::socket_t & socket, std::string const& string) 
{
    zmq::message_t message(string.size());
    std::memcpy(message.data(), string.data(), string.size());
    bool rc = socket.send(message);
    return (rc);
}
示例#13
0
 /** Send empty message. */
 inline bool send(zmq::socket_t &s, const empty &v, int flags) 
 {
   zmq::message_t msg(0);
   
   IB_FIRST_PART(s.send(msg, flags));
   return true;    
 }
示例#14
0
void safeSend(zmq::socket_t &sock, const char *buf, size_t buflen, MessageHeader header) {
	char tnam[100];
	int pgn_rc = pthread_getname_np(pthread_self(),tnam, 100);
	assert(pgn_rc == 0);

	//if (buflen>10) {FileLogger fl(program_name); fl.f() << tnam << " Sending\n"; }

	enum send_stage {e_sending_dest, e_sending_source, e_sending_data} stage = e_sending_data;
	if (header.dest || header.source) {
		stage = e_sending_source;
	}

	while (!MessagingInterface::aborted()) {
		try {
			//if (buflen>10){FileLogger fl(program_name); fl.f() << tnam << " safeSend() sending " << buf << "\n"; }
			if (stage == e_sending_source) {
				zmq::message_t msg(sizeof(MessageHeader));
				memcpy(msg.data(), &header, sizeof(MessageHeader) );
				sock.send(msg, ZMQ_SNDMORE);
				stage = e_sending_data;
			}
			if (stage == e_sending_data ) {
				zmq::message_t msg(buflen);
				memcpy(msg.data(), buf, buflen );
				sock.send(msg);
			}
			break;
		}
		catch (zmq::error_t) {
			if (zmq_errno() != EINTR && zmq_errno() != EAGAIN) {
				{
					FileLogger fl(program_name);
					fl.f()  << tnam << " safeSend error " << errno << " " << zmq_strerror(errno) << "\n";
				}
				if (zmq_errno() == EFSM) throw;
				usleep(10);
				continue;
			} else {
				{
					FileLogger fl(program_name);
					fl.f()  << tnam << " safeSend error " << errno << " " << zmq_strerror(errno) << "\n";
				}
				usleep(10);
			}
		}
	}
}
示例#15
0
void handleOp(zmq::socket_t &socket, int opCode) {
    std::string s_req, trace, line;
    std::cout<<"Trace: ";
    std::getline(std::cin, trace);
    Request req;
    Id id;
    Person person;
    Request_Header_Type type;
    switch (opCode) {
        case 1:
            type = Request_Header_Type_LOOKUP;
            std::cout<<"id: ";
            line.clear();
            std::getline(std::cin, line);
            id = makeId(fromString<int>(line));
            req = makeRequest(type, id, person, false, trace);
            break;
        case 3:
            type = Request_Header_Type_REMOVE;
            std::cout<<"id: ";
            line.clear();
            std::getline(std::cin, line);
            id = makeId(fromString<int>(line));
            req = makeRequest(type, id, person, false, trace);
            break;
        case 2:
            {
                type = Request_Header_Type_INSERT;
                std::cout<<"id: ";
                line.clear();
                std::getline(std::cin, line);
                id = makeId(fromString<int>(line));
                line.clear();
                std::cout<<"Name: ";
                std::getline(std::cin, line);
                std::string ph, ovr;
                std::cout<<"Phone: ";
                std::getline(std::cin, ph);
                std::cout<<"Overwrite: (y/n) ";
                std::getline(std::cin, ovr);
                person = makePerson(line, ph);
                req = makeRequest(type, id, person, ovr.compare("y") == 0,
                        trace);
                break;
            }
    };
    std::cout<<"Request: "<<requestToString(req);
    TRACE(std::cout, "");
    req.SerializeToString(&s_req);
    zmq::message_t z_req(s_req.size());
    memcpy(z_req.data(), (void *)s_req.data(), s_req.size());
    socket.send(z_req);
    zmq::message_t z_resp;
    socket.recv(&z_resp);
    std::string s_resp((char *)z_resp.data(), z_resp.size());
    Response resp;
    resp.ParseFromString(s_resp);
    std::cout<<"Response = "<<responseToString(resp);
}
	void SampleSensor::Update(TimeValue dt)
	{
		//check to see if it is time to write an update to this sensor
		m_sampleTimeLeft -= dt;

		//if we still have time left, skip writing an update
		if (m_sampleTimeLeft > 0.0) 
			return;

		//Sending the image is dependent on the frame rate and if the user has closed the connection
		if((frame % (int) (100 / sendRate) == 0) && running) {
			// Get Video Data and Send as ZMQ Message
			std::vector<SensorPtr> sensors = SensorManager::GetSingleton().GetAllSensors();
			for (uint32 i = 0; i < sensors.size(); ++i)
			{
				if (sensors[i]->GetSensorType() != "CameraSensor")
					continue;

				CameraSensor* pCam = static_cast<CameraSensor*>(sensors[i].Get());
		
				const std::vector<LensData>& lens = pCam->GetLensData();
				if (lens.size() == 0)
					continue;

				const LensData& thisLens = lens[0];
				const LensParams & lensParams = pCam->GetLensParams()[0];

				if (thisLens.m_renderRequest.m_pOutputBuffer != NULL) {
					//Pull the dimensions of the camera
					int size, sizeX, sizeY;
					sizeX = lensParams.m_resolutionX;
					sizeY = lensParams.m_resolutionY;
					size = sizeX * sizeY * 3;
				
					//Make a buffer for the compressed jpeg
					void *buf = malloc(size);

					//Set the Quality Factor
					jpge::params params;
					params.m_quality = quality_factor;

					//Compress the image to improve transfer speed
					if(compress_image_to_jpeg_file_in_memory(buf, size, sizeX, sizeY, 3, thisLens.m_renderRequest.m_pOutputBuffer, params)) {
						//Put the compressed data into a ZMQ message and send it over the socket
						zmq::message_t image (size);
						memcpy((void *) image.data(), buf, size);
						socket_.send (image);
					}
					else {
						LogMessage("Failed to compress image", kLogMsgError);
					}
				}
			}
		}
		frame++;
		
		
		m_sampleTimeLeft += m_sampleStep;
	}
示例#17
0
static bool
s_sendobj (zmq::socket_t & socket, Message& obj) {

    msgPtr message = obj.fillmessage();

    bool rc = socket.send (*message);
    return (rc);
}
示例#18
0
    bool sendStringPart(zmq::socket_t & socket, const std::string & string)
    {
      // Taken from zhelpers.hpp
      zmq::message_t message(string.size());
      memcpy(message.data(), string.data(), string.size());

      return socket.send(message, ZMQ_SNDMORE);
    }
示例#19
0
void sendStr(zmq::socket_t& socket, string const & s, int flags = 0) {
	zmq::message_t reply(s.size() * sizeof(string::value_type));
	std::memcpy(reply.data(), s.c_str(), s.size());
	
	if (!socket.send(reply, flags)) {
		std::cerr << "Envoi KO" << std::endl;
	}
}
示例#20
0
	static bool s_sendmore(zmq::socket_t &socket, const std::string &msg)
	{
		zmq::message_t message(msg.size());
		memcpy(message.data(), msg.data(), msg.size());

		bool sent = socket.send(message, ZMQ_SNDMORE);
		return sent;
	}
示例#21
0
//  Sends string as 0MQ string, as multipart non-terminal
static bool
s_sendmore (zmq::socket_t & socket, const std::string & string) {

    zmq::message_t message(string.size());
    memcpy (message.data(), string.data(), string.size());

    bool rc = socket.send (message, ZMQ_SNDMORE);
    return (rc);
}
//  Sends string as 0MQ string, as multipart non-terminal
static bool
s_sendmore (zmq::socket_t & socket, const std::string & data)
{
  char * buff = (char*)malloc(data.size());
  memcpy(buff, data.c_str(), data.size());
  zmq::message_t message((void*)buff, data.size(), s_free, 0);
  bool rc = socket.send(message, ZMQ_SNDMORE);
  return (rc);
}
示例#23
0
// capacity request
void process_status_request(zmq::socket_t& status, int& number_of_workers) {
  // null request
  zmq::message_t incoming_msg;
  status.recv(&incoming_msg);

  // send current capacity
  zmq::message_t status_msg(sizeof(number_of_workers));
  memcpy(status_msg.data(), &number_of_workers, sizeof(number_of_workers));
  status.send(status_msg);
}
示例#24
0
 /** Send string. */
 inline bool send(zmq::socket_t &s, const std::string &v, int flags) 
 {
   zmq::message_t msg(v.size());
   if (!v.empty()) {
     memcpy(msg.data(), v.c_str(), v.size());
   }
   
   IB_FIRST_PART(s.send(msg, flags));
   return true;
 }
示例#25
0
static bool
s_send2 (zmq::socket_t & socket, uchar* & u)
{

    zmq::message_t message(sizeof(u));
    memcpy (message.data(), u, sizeof(u));

    bool rc = socket.send (message);
    return (rc);
}
 bool handle_response() {
   auto response = socket.recv_all(0).front().str();
   logging::DEBUG(uuid + ":" + response.substr(0, 1));
   switch(response.front()) {
     case 'I': //INFO for the camera
       socket.send(std::string("N"), ZMQ_DONTWAIT);
       settings = response.substr(1);
       return true;
     case 'N': //NEXT camera image name
       next = response.substr(1);
       if(next.size())
         socket.send(std::string("C" + next), ZMQ_DONTWAIT);
       break;
     case 'W': //WAIT so many seconds before asking again
       settings = response.substr(1);
       wait_until = std::time(nullptr) + 1; //TODO: parse out the interval
       return true;
     case 'C': //CAMERA image data is here
       {
         auto destination = www_dir + "/cameras/" + uuid + "/" + next.substr(next.front() == '/' ? 1 : 0);
         auto db = www_dir + "/cameras/" + uuid + ".db";
         if(!system(("mkdir -p $(dirname " + destination + ")").c_str())) {
           std::fstream output(destination, std::ios::out | std::ios::binary | std::ios::trunc);
           output.write(response.data() + 1, response.size() - 1);
           update_record(db, destination);
           photo_count = record_count(db);
           logging::INFO("Wrote " + destination);
         }
       }
       socket.send(std::string("D" + next), ZMQ_DONTWAIT);
       next = "";
       break;
     case 'E': //ERROR came in
       settings = next = "";
       wait_until = std::time(nullptr) + 1;
       break;
     default:
       logging::WARN("Unrecognized response: " + response);
       break;
   }
   return false;
 }
inline bool send(zmq::socket_t & socket, tile_protocol const& tile)
{
   std::string buf;
   if (serialise(tile, buf))
   {
      zmq::message_t msg(buf.size()); 
      std::memcpy(msg.data(),buf.data(),buf.size());
      return socket.send(msg);
   }
   return false;
}
示例#28
0
/*
 * return number of bytes sent, negative if error
 */
int send_msg(zmq::socket_t &sock, uint8_t *data, size_t len, int flag){
  
  int nbytes;
  try{
    nbytes = sock.send(data, len, flag);
  }catch(zmq::error_t e){
    //LOG(NOR, stderr, "send failed: %s\n", e.what());
    return -1;
  }
  return nbytes;
}
inline bool send_to(const std::string & id, zmq::socket_t & socket, tile_protocol const& tile) {
   std::string buf;
   if (serialise(tile, buf)) {
      zmq::message_t msg(id.size()); 
      std::memcpy(msg.data(),id.data(),id.size());

      // send the ID of the receiver first
      if (!socket.send(msg, ZMQ_SNDMORE)) return false;
      msg.rebuild();

      // then a blank spacer message
      if (!socket.send(msg, ZMQ_SNDMORE)) return false;
      msg.rebuild(buf.size());
    
      // then send the message itself
      std::memcpy(msg.data(),buf.data(),buf.size());
      return socket.send(msg);
   }
   return false;  
}
示例#30
0
void _send(zmq::socket_t & socket, std::list<zmq::message_t*> &msg_list) {
    std::list<zmq::message_t*>::const_iterator last = --msg_list.end();
    int i = 0;
    for (std::list<zmq::message_t*>::const_iterator it = msg_list.begin();
         it != msg_list.end();
         ++it) {
        int flags = (it == last) ? 0 : ZMQ_SNDMORE;
        DLOG(INFO) << "sending msg " << i++ << " flags " << flags;
        socket.send(*(*it), flags);
    }
}