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
   bool recv(zmq::socket_t & socket) {
      clear();
      while(1) {
         zmq::message_t message(0);
         try {
            if (!socket.recv(&message, 0)) {
               return false;
            }
         } catch (zmq::error_t error) {
            //std::cout << "E: " << error.what() << std::endl;
            return false;
         }
         char *data = reinterpret_cast<char*>(message.data());
         if (message.size() == 17 && data[0] == 0) {
            push_back(encode_uuid(msg_to_string(message)));
         } else {
            push_back(msg_to_string(message));
         }
		 boost::int64_t more;
         size_t more_size = sizeof(more);
         socket.getsockopt(ZMQ_RCVMORE, &more, &more_size);
         if (!more) {
            break;
         }
      }
      return true;
   }
Пример #3
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();
    }
  }
}
void OTSocket::Listen(const OTString &strBind)
{
	if (NULL != m_pSocket)
		delete m_pSocket;
//	m_pSocket = NULL;
	m_pSocket = new zmq::socket_t(*m_pContext, ZMQ_REP);  // RESPONSE socket (Request / Response.)
	OT_ASSERT_MSG(NULL != m_pSocket, "OTSocket::Listen: new zmq::socket(context, ZMQ_REP)");
	
	OTString strTemp(strBind); // In case m_strBindPath is what was passed in. (It happens.)
	m_strBindPath.Set(strTemp); // In case we have to close/reopen the socket to finish a send/receive.
	
	// ------------------------
	//  Configure socket to not wait at close time
    //
	const int linger = 0; // close immediately
	m_pSocket->setsockopt (ZMQ_LINGER, &linger, sizeof (linger));
    /*
     int zmq_setsockopt (void *socket, int option_name, const void *option_value, size_t option_len);
     
     Caution: All options, with the exception of ZMQ_SUBSCRIBE, ZMQ_UNSUBSCRIBE and ZMQ_LINGER, only take effect for subsequent socket bind/connects.     
     */
    
	// ------------------------
    
	m_pSocket->bind(strBind.Get());
}
Пример #5
0
  /*
   * return number of bytes received, negative if error, 0 for received nothing,
   *  which should be treated as error
   */
  int32_t RecvMsg(zmq::socket_t &sock, boost::shared_array<uint8_t> &data,
      bool *_more){
    zmq::message_t msgt;
    int nbytes;
    try{
      nbytes = sock.recv(&msgt);
    }catch(zmq::error_t &e){
      LOG(ERROR) << "RecvMsg error = " << e.what();
      return -1;
    }

    if(nbytes == 0) return 0;

    size_t len = msgt.size();    
    uint8_t *dataptr;
    try{
      dataptr = new uint8_t[len];
    }catch(std::bad_alloc &e){
      return -1;
    }
    
    memcpy(dataptr, msgt.data(), len);
    data.reset(dataptr);

    if(_more != NULL){
      int more_recv;
      size_t s = sizeof(int);
      sock.getsockopt(ZMQ_RCVMORE, &more_recv, &s);
      *_more = (more_recv == 1) ? true : false;
    }
    return len;
  }
Пример #6
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);
}
	SampleSensor::SampleSensor( VaneID specificId, SensorStaticAssetParams& params, DynamicAssetParams& dynamicParams )
		: Sensor(specificId, params, dynamicParams)
	{
		
		//Get the current IP address
		String ip;
		if(!getMyIP(ip)) {
			LogMessage("Failed to get IP", kLogMsgError);
			running = false;
		}
		else {
			LogMessage(ip);

			ipaddr = ip;
			running = true;

			//Bind to the computer's IP adress
			socket_.init(context_, ZMQ_PAIR);
			socket_.bind("tcp://" + ip + ":9000");

			LogMessage("Connected", kLogMsgSpecial);
		}

		frame = 0;
		sendRate = 15;
		quality_factor = 85;

		
		//cast to our specific type of asset params, and grab data 
		const SampleSensorStaticAssetParams& sampleParams = static_cast<const SampleSensorStaticAssetParams&>( params );
		m_sampleIntData = sampleParams.m_intData;
	}
Пример #8
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);
}
Пример #9
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);
}
Пример #10
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);
    }    
}
Пример #11
0
bool Server::getRequest (zmq::socket_t &socket, pb::RequestEnvelope &envelope) {
  long long more;
  size_t sz = sizeof (more);
  zmq::message_t request;
  
  socket.recv (&request);
  socket.getsockopt (ZMQ_RCVMORE, &more, &sz);
  bool isAnotherRequest = more != 0;
  envelope.ParseFromArray (request.data(), request.size());
  
  return isAnotherRequest;
}
Пример #12
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);
    }

}
Пример #13
0
bool ServerInterface::SendMove(enum Tetromino::Move move, int pieceId, zmq::socket_t& commandSocket) const {
    std::string const* moveCommandS = m_factory.CreateMoveMessage(move, pieceId);
    zmq::message_t moveCommand (moveCommandS->size());
    memcpy(static_cast<void*>(moveCommand.data()), moveCommandS->data(), 
                                moveCommandS->size());
    delete moveCommandS;
    commandSocket.send(moveCommand);

    zmq::message_t reply;
    commandSocket.recv(&reply);
    std::string replyS (static_cast<char const*>(reply.data()), reply.size());
    return m_factory.ParseMoveReply(replyS);
}
Пример #14
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;
    }
}
Пример #15
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);
    }

}
Пример #16
0
Файл: zmq.cpp Проект: plq/zmq
void recv_multipart(zmq::socket_t &socket) {
    int64_t more=-1;
    size_t more_size = sizeof (more);
    while(more) {
        zmq::message_t response;
        socket.recv(&response);

        std::string response_str((const char *)response.data(),
                                                             response.size());
        cout << response_str << endl;

        socket.getsockopt(ZMQ_RCVMORE, &more, &more_size);
    }
}
Пример #17
0
// relay data from workers to frontend
void process_backend(zmq::socket_t& frontend, zmq::socket_t& backend) {
  int64_t more;
  size_t moresz;
  moresz = sizeof(more);

  while(true) {
    zmq::message_t worker_msg;
    backend.recv(&worker_msg);
    backend.getsockopt(ZMQ_RCVMORE, &more, &moresz);
    frontend.send(worker_msg, more ? ZMQ_SNDMORE : 0);
    if(!more) {
      break;
    }
  }
}
Пример #18
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;    
 }
 camera_t(zmq::context_t& context, const std::string& endpoint, const std::string& uuid, const std::string& www_dir):
   socket(context, ZMQ_REQ), uuid(uuid), photo_count(0), settings(), next(), wait_until(0), www_dir(www_dir) {
   photo_count = record_count(www_dir + "/cameras/" + uuid + ".db");
   while(this->uuid.size() && this->uuid.back() == '\0')
     this->uuid.pop_back();
   socket.connect(endpoint.c_str());
 }
 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;
   }
 }
Пример #21
0
//  Set simple random printable identity on socket
//
static void
s_set_id (zmq::socket_t & socket)
{
    char identity [10];
    sprintf (identity, "%04X-%04X", within (0x10000), within (0x10000));
    socket.setsockopt(ZMQ_IDENTITY, identity, strlen (identity));
}
Пример #22
0
    Message receive(zmq::socket_t& socket)
    {
      std::vector<std::string> address;
      std::string frame = receiveString(socket);
      // Do we have an address?
      while (frame.compare("") != 0)
      {
        address.push_back(frame);
        frame = receiveString(socket);
      }
      // address is a stack, so reverse it to get the right way around
      std::reverse(address.begin(), address.end());

      // We've just read the delimiter, so now get subject
      auto subjectString = receiveString(socket);
      //the underlying representation is (explicitly) an int so fairly safe
      Subject subject = (Subject)detail::unserialise<std::uint32_t>(subjectString);
      std::vector<std::string> data;
      while (true)
      {
        int isMore = 0;
        size_t moreSize = sizeof(isMore);
        socket.getsockopt(ZMQ_RCVMORE, &isMore, &moreSize);
        if (!isMore)
          break;
        data.push_back(receiveString(socket));
      }
      return Message(address, subject, data);
    }
Пример #23
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);
}
Пример #24
0
inline bool recv (zmq::socket_t & socket, tile_protocol & tile)
{
   zmq::message_t msg;
   socket.recv(&msg);
   std::string buf(static_cast<char*>(msg.data()),msg.size());
   return unserialise(buf, tile);
}
Пример #25
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);
			}
		}
	}
}
Пример #26
0
// 0 for received nothing
int recv_msg_async(zmq::socket_t &sock, boost::shared_array<uint8_t> &data)
{
    zmq::message_t msgt;
    int nbytes;
    try{
      nbytes = sock.recv(&msgt, ZMQ_DONTWAIT);
    }catch(zmq::error_t e){
      return -1;
    }

    if(nbytes == 0){
      if(zmq_errno() == EAGAIN)
	return 0;
      else
	return -1;
    }

    size_t len = msgt.size();    
    uint8_t *dataptr;
    try{
      dataptr = new uint8_t[len];
    }catch(std::bad_alloc e){
      return -1;
    }
    
    memcpy(dataptr, msgt.data(), len);
    data.reset(dataptr);
    return len;
}
Пример #27
0
/*
 * return number of bytes received, negative if error, 0 for received nothing, which should be treated as error
 */
int recv_msg(zmq::socket_t &sock, boost::shared_array<uint8_t> &data)
{
    zmq::message_t msgt;
    int nbytes;
    try{
      nbytes = sock.recv(&msgt);
    }catch(zmq::error_t e){
      //LOG(NOR, stderr, "recv failed: %s\n", e.what());
      return -1;
    }

    if(nbytes == 0) return 0;

    size_t len = msgt.size();    
    uint8_t *dataptr;
    try{
      dataptr = new uint8_t[len];
    }catch(std::bad_alloc e){
      //LOG(DBG, stderr, "can not allocate memory!\n");
      return -1;
    }
    
    memcpy(dataptr, msgt.data(), len);
    data.reset(dataptr);
    return len;
}
Пример #28
0
//  Receive 0MQ string from socket and convert into string
static std::string
s_recv (zmq::socket_t & socket) {

    zmq::message_t message;
    socket.recv(&message);
    return std::string(static_cast<char*>(message.data()), message.size());
}
Пример #29
0
bool recursive_receive(zmq::socket_t& receiving_socket, zmq::message_t& message,
                       const REQ& req, RES& response, bool& succeed) {
  bool rc = receiving_socket.recv(&message);

  if (rc) {
    auto serialized_resp = kZmqUtil->message_to_string(message);
    response.ParseFromString(serialized_resp);

    if (req.request_id() == response.response_id()) {
      succeed = true;
      return false;
    } else {
      return true;
    }
  } else {
    // timeout
    if (errno == EAGAIN) {
      succeed = false;
    } else {
      succeed = false;
    }

    return false;
  }
}
Пример #30
0
/**
 * 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;
}