void Transmitter::set_qos() { ReturnCode_t retcode = publisher()->get_default_datawriter_qos(m_writer_qos); publisher().check(retcode, "Publisher::get_default_datawriter_qos"); TopicQos topic_qos; retcode = m_topic->get_qos(topic_qos); m_topic.check(retcode, "Topic::get_qos"); retcode = publisher()->copy_from_topic_qos(m_writer_qos, topic_qos); publisher().check(retcode, "Publisher::copy_from_topic_qos"); m_writer_qos.latency_budget.duration.sec = m_qos.qos.latency_budget.duration.sec; m_writer_qos.latency_budget.duration.nanosec = m_qos.qos.latency_budget.duration.nanosec; m_writer_qos.transport_priority.value = m_qos.qos.transport_priority.value; /* For reliable transport, the transmitter writer * needs to set extra policies for its resource * limits, which avoids excessive memory growth * and invokes flow control if needed */ if (m_writer_qos.reliability.kind == DDS::RELIABLE_RELIABILITY_QOS) { m_writer_qos.history.kind = DDS::KEEP_ALL_HISTORY_QOS; m_writer_qos.resource_limits.max_samples = 100; } }
int main(int argc, char * argv[]) { Miro::Log::init(argc, argv); kn::DdsSupport::init(argc, argv); kn::DdsEntitiesFactorySvc ddsEntities; ddsEntities.init(argc, argv); Miro::ShutdownHandler shutdownHander; { kn::DdsTypedSupplier<HelloWorld> publisher("Example HelloWorld"); HelloWorldPrinter printer; kn::DdsTypedConnector<HelloWorld, HelloWorldPrinter> subscriber(&printer, "Example HelloWorld"); for (unsigned int i = 0; i < 10000; ++i) { /* Modify the data to be sent here */ sprintf(publisher.event().msg, "Hello World! (%d)", i); publisher.sendEvent(); kn::this_thread::sleep_for(kn::microseconds(10000)); if (shutdownHander.isShutdown()) { break; } } } ddsEntities.fini(); return 0; }
int main () { // Prepare our context and publisher zmq::context_t context (1); zmq::socket_t publisher (context, ZMQ_PUB); publisher.bind("tcp://*:5556"); // publisher.bind("ipc://weather.ipc"); // Initialize random number generator srandom ((unsigned) time (NULL)); while (1) { int zipcode, temperature, relhumidity; // Get values that will fool the boss zipcode = within (100000); temperature = within (215) - 80; relhumidity = within (50) + 10; // Send message to all subscribers zmq::message_t message(20); snprintf ((char *) message.data(), 20 , "%05d %d %d", zipcode, temperature, relhumidity); publisher.send(message); } return 0; }
int main () { zmq::context_t context(1); // Subscriber tells us when it's ready here zmq::socket_t sync(context, ZMQ_PULL); sync.bind("tcp://*:5564"); // We send updates via this socket zmq::socket_t publisher (context, ZMQ_PUB); publisher.bind("tcp://*:5565"); // Wait for synchronization request s_recv (sync); // Now broadcast exactly 10 updates with pause int update_nbr; for (update_nbr = 0; update_nbr < 10; update_nbr++) { std::ostringstream oss; oss << "Update "<< update_nbr ; s_send (publisher, oss.str()); sleep (1); } s_send (publisher, "END"); sleep (1); // Give 0MQ/2.0.x time to flush output return 0; }
int main() { // Prepare our context and publisher zmq::context_t context(1); zmq::socket_t publisher(context, ZMQ_REP); publisher.bind("tcp://*:5556"); // Create the fake walk std::string walk[800]; int i; for (i = 0; i < 800; i++) { walk[i] = std::to_string(i) + " " + std::to_string(i); } i = 0; while (true) { // Just repeat the walk if (i >= 800) i = 0; // Send envelope s_sendmore(publisher, "pos"); s_send(publisher, walk[i]); // Synchronize with client usleep(10); i++; } return 0; }
void Servo::Serv() { zmq::socket_t publisher(zContext, ZMQ_PUB); std::string hostmask = "tcp://"; while (!lservAddr.try_lock()) std::this_thread::sleep_for(std::chrono::milliseconds(50)); if (!servAddr.empty()) hostmask.append(servAddr); else hostmask.append("127.0.0.1"); lservAddr.unlock(); hostmask.append(":56556"); publisher.bind(hostmask.c_str()); connected = true; while (connected) { while(!lock.try_lock()) std::this_thread::sleep_for(std::chrono::milliseconds(50)); if (!buffer.empty()) { auto it = buffer.begin(); zmq::message_t message(it->length()+1); strcpy_s((char*)message.data(), (size_t)(it->length() + 1), it->c_str()); buffer.pop_front(); lock.unlock(); publisher.send(message,ZMQ_DONTWAIT); } else lock.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(20)); } publisher.close(); }
int ACE_TMAIN(int argc, ACE_TCHAR* argv[]) { OpenDDS::DCPS::set_DCPS_debug_level( 0); int status = 0; try { Publisher publisher( argc, argv, 0); publisher.run(); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("(%P|%t) FATAL: Publisher - CORBA problem detected.\n"); status = -1; } catch (const std::exception& ex) { ACE_ERROR ((LM_ERROR, ACE_TEXT("(%P|%t) FATAL: Publisher - ") ACE_TEXT("%C exception caught in main().\n"), ex.what() )); status = -2; } catch(...) { ACE_ERROR ((LM_ERROR, ACE_TEXT("(%P|%t) FATAL: Publisher - ") ACE_TEXT("Unspecified exception caught in main() - panic.\n") )); status = -3; } return status; }
int main() { QtMobility::QValueSpacePublisher publisher(QString()); QtMobility::QValueSpaceSubscriber subcriber(QString()); QtMobility::QSystemDeviceInfo deviceInfo; QtMobility::QSystemNetworkInfo networkInfo; }
bool try_initialize_more (Ekiga::ServiceCore& core, int* /*argc*/, char** /*argv*/[]) { boost::shared_ptr<Ekiga::PresenceCore> presence_core = core.get<Ekiga::PresenceCore> ("presence-core"); boost::shared_ptr<Ekiga::CallCore> call_core = core.get<Ekiga::CallCore> ("call-core"); boost::shared_ptr<Ekiga::PersonalDetails> details = core.get<Ekiga::PersonalDetails> ("personal-details"); if (presence_core && call_core && details) { boost::shared_ptr<Avahi::PresencePublisher> publisher (new Avahi::PresencePublisher (core, *details, *call_core)); if (core.add (publisher)) { presence_core->add_presence_publisher (publisher); result = true; } boost::shared_ptr<Avahi::Cluster> cluster = Avahi::Cluster::create (core); if (core.add (cluster)) { presence_core->add_cluster (cluster); result = true; } } return result; }
int main(int argc, char * argv[]) { Miro::Robot::init(argc, argv); kn::DdsEntitiesFactorySvc ddsEntities; ddsEntities.init(argc, argv); int bufferSize = 10; if (argc >= 2) bufferSize = atoi(argv[1]); if (argc >= 3) topic = argv[2]; Miro::ShutdownHandler shutdownHandler; { kn::DdsTypedSupplier<HelloWorld> publisher(topic); for (unsigned int i = 0; i < 10000; ++i) { /* Modify the data to be sent here */ sprintf(publisher.event().msg, "Hello World! (%d)", i); publisher.event().id = i; publisher.event().buffer.maximum(bufferSize); publisher.event().buffer.length(bufferSize); publisher.sendEvent(); kn::this_thread::sleep_for(kn::microseconds(10000)); if (shutdownHandler.isShutdown()) { break; } } } ddsEntities.fini(); return 0; }
TInt CBulkOnlyTransport::SendDataTxCmdL(const MClientCommandServiceReq* aCommand, TDesC8& aData, TUint aPos, TInt& aLen) { __MSFNLOG TInt r = KErrNone; SendCbwL(aCommand, TBotCbw::EDataOut, aLen); TInt len = aLen; TInt length = 0; iBulkDataTd.SetZlpStatus(RUsbTransferDescriptor::ESuppressZlp); while (len) { TPtr8 senddata = iBulkDataTd.WritableBuffer(); senddata.Append(aData.Ptr() + length + aPos, len > KResponsePacketSize? KResponsePacketSize : len); iBulkDataTd.SaveData(senddata.Length()); iBulkPipeOut.Transfer(iBulkDataTd, iStatus); User::WaitForRequest(iStatus); if (iStatus.Int() != KErrNone) { if (iStatus.Int() == KErrUsbStalled) { __BOTPRINT(_L("SendDataTxCmdL ClearRemoteStall")); iBulkPipeOut.ClearRemoteStall(); #ifdef MASSSTORAGE_PUBLISHER TMsPublisher publisher(TMsPublisher::KStallProperty); #endif break; } DoResetRecovery(); __BOTPRINT1(_L("Usb transfer error %d"), r); User::Leave(KErrGeneral); } if(len > KResponsePacketSize) { len -= KResponsePacketSize; length += KResponsePacketSize; } else { length += len; len = 0; } } ReceiveCswL(); TUint32 lenSent = 0; r = ProcessOutTransferL(lenSent); aLen = lenSent; return r; }
TInt CBulkOnlyTransport::SendDataRxCmdL(const MClientCommandServiceReq* aCommand, TDes8& aCopyBuf, TInt& aLen) { __MSFNLOG TInt r = KErrNone; SendCbwL(aCommand, TBotCbw::EDataIn, aLen); // store initial length as data is appended to the buffer TInt startPos = aCopyBuf.Length(); TInt len = aLen; while (len) { if(len > KResponsePacketSize) iBulkDataTd.SaveData(KResponsePacketSize); else iBulkDataTd.SaveData(len); iBulkPipeIn.Transfer(iBulkDataTd, iStatus); User::WaitForRequest(iStatus); r = iStatus.Int(); if (r != KErrNone) { if (r == KErrUsbStalled) { __BOTPRINT(_L("SendDataRxCmdL ClearRemoteStall")); iBulkPipeIn.ClearRemoteStall(); #ifdef MASSSTORAGE_PUBLISHER TMsPublisher publisher(TMsPublisher::KStallProperty); #endif break; } DoResetRecovery(); __BOTPRINT1(_L("Usb transfer error %d"),r); User::Leave(KErrGeneral); } TPtrC8 data = iBulkDataTd.Buffer(); aCopyBuf.Append(data.Ptr(), data.Length()); if(len > KResponsePacketSize) len -= KResponsePacketSize; else len = 0; } ReceiveCswL(); TUint32 lenReceived = 0; r = ProcessInTransferL(lenReceived); aLen = lenReceived; aCopyBuf.SetLength(startPos + lenReceived); return r; }
void Transceiver::set_qos() { // set writer Qos ReturnCode_t retcode = publisher()->get_default_datawriter_qos(m_writer_qos); publisher().check(retcode, "Publisher::get_default_datawriter_qos"); TopicQos topic_qos; retcode = m_topic->get_qos(topic_qos); m_topic.check(retcode, "Topic::get_qos"); retcode = publisher()->copy_from_topic_qos(m_writer_qos, topic_qos); publisher().check(retcode, "Publisher::copy_from_topic_qos"); m_writer_qos.latency_budget.duration.sec = m_qos.writer_qos.latency_budget.duration.sec; m_writer_qos.latency_budget.duration.nanosec = m_qos.writer_qos.latency_budget.duration.nanosec; m_writer_qos.transport_priority.value = m_qos.writer_qos.transport_priority.value; // set reader Qos retcode = subscriber()->get_default_datareader_qos(m_reader_qos); subscriber().check(retcode, "Subscriber::get_default_datareader_qos"); retcode = m_echo_topic->get_qos(topic_qos); m_echo_topic.check(retcode, "Topic::get_qos"); retcode = subscriber()->copy_from_topic_qos(m_reader_qos, topic_qos); subscriber().check(retcode, "Subscriber::copy_from_topic_qos"); m_reader_qos.history.depth = m_qos.reader_qos.history.depth; m_reader_qos.latency_budget.duration.sec = m_qos.reader_qos.latency_budget.duration.sec; m_reader_qos.latency_budget.duration.nanosec = m_qos.reader_qos.latency_budget.duration.nanosec; }
Transmitter::Transmitter(Partition& partition) : m_partition(partition), m_qos_query(qos_reader()), m_topic(participant()), m_writer(publisher(), m_topic), m_writer_thread(*this), m_active(false), m_config_number(0) { // cout << "Transmitter::Transmitter(" << partition_id() << ")" << endl; }
void CBulkOnlyTransport::DoResetRecovery() { __MSFNLOG __BOTPRINT(_L("BOT RESET RECOVERY")); #ifdef MASSSTORAGE_PUBLISHER TMsPublisher publisher(TMsPublisher::KBotResetProperty); #endif Reset(); iBulkPipeIn.ClearRemoteStall(); iBulkPipeOut.ClearRemoteStall(); }
/** * @brief A timer operation * This operation can be triggered by a periodic timer * Bind this operation to a periodic timer in the JSON configuration */ void Component_2::timer_function() { boost::random::mt19937 rng; boost::random::uniform_int_distribution<> loop_iteration_random(800000 * 0.6, 800000); int loop_max = loop_iteration_random(rng); // Business Logic for Timer_2_operation for(int i=0; i < loop_max; i++) { double result = 0.0; double x = 41865185131.214415; double y = 562056205.1515; result = x*y; } publisher("publisher_port")->send("Component_2"); std::cout << "Component 2 : Timer : Published message: Component_2" << std::endl; }
int ACE_TMAIN(int argc, ACE_TCHAR* argv[]) { try { // Initialize DDS. DDS::DomainParticipantFactory_var dpf = TheParticipantFactoryWithArgs( argc, argv); // Initialize the test. const Test::Options options( argc, argv); // Create the publisher thingie. Test::Publisher publisher( options); if( OpenDDS::DCPS::DCPS_debug_level > 0) { std::stringstream buffer; buffer << options.transportType(); ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%P|%t) publisher_main() - ") ACE_TEXT("started with transport %C(%d), id %d.\n"), buffer.str().c_str(), options.transportKey(), options.publisherId() )); } // Execute the test. publisher.run(); } catch( CORBA::Exception& /* e */) { ACE_ERROR((LM_ERROR, ACE_TEXT("(%P|%t) publisher_main() - ") ACE_TEXT("CORBA exception caught during processing.\n") )); return 1; } catch (const Test::Exception& e) { ACE_ERROR((LM_ERROR, ACE_TEXT("(%P|%t) publisher_main() - ") ACE_TEXT("Test exception caught during processing: %C.\n"), e.what() )); return 1; } return 0; }
QString RDLogLine::resolveWildcards(QString pattern) { pattern.replace("%n",QString().sprintf("%06u",cartNumber())); pattern.replace("%h",QString().sprintf("%d",effectiveLength())); pattern.replace("%g",groupName()); pattern.replace("%t",title()); pattern.replace("%a",artist()); pattern.replace("%l",album()); pattern.replace("%y",year().toString("yyyy")); pattern.replace("%b",label()); pattern.replace("%c",client()); pattern.replace("%e",agency()); pattern.replace("%m",composer()); pattern.replace("%p",publisher()); pattern.replace("%u",userDefined()); return pattern; }
/** * @brief A server operation * This operation can be bound to a server and requested by some client * Bind this operation to a server in the JSON configuration */ void Component_2::server_function() { std::string request = server("server")->message(); std::cout << "Component 2 : Server : Received request: " << request << std::endl; boost::random::mt19937 rng; boost::random::uniform_int_distribution<> loop_iteration_random(600000 * 0.6, 600000); int loop_max = loop_iteration_random(rng); // Business Logic for Service_Server_operation for(int i=0; i < loop_max; i++) { double result = 0.0; double x = 41865185131.214415; double y = 562056205.1515; result = x*y; } publisher("publisher_port")->send("Component_2"); std::cout << "Component 2 : Server : Published message: Component_2" << std::endl; server("server")->set_response("Component_2"); }
void CBulkOnlyTransport::ReceiveCswL() { __MSFNLOG iBulkInCswTd.SaveData(KCswPacketSize); iBulkPipeIn.Transfer(iBulkInCswTd, iStatus); User::WaitForRequest(iStatus); TInt r = iStatus.Int(); if (r != KErrNone) { if (r == KErrUsbStalled) { __BOTPRINT(_L("Csw: Clearing BulkIn stall")); iBulkPipeIn.ClearRemoteStall(); iBulkInCswTd.SaveData(KCswPacketSize); iBulkPipeIn.Transfer(iBulkInCswTd, iStatus); User::WaitForRequest(iStatus); #ifdef MASSSTORAGE_PUBLISHER TMsPublisher publisher(TMsPublisher::KStallProperty); #endif r = iStatus.Int(); if (r == KErrUsbStalled) { __BOTPRINT(_L("Csw: BulkIn stalled")); DoResetRecovery(); } } // Handle other usb error and retry failures if (r != KErrNone) { __BOTPRINT1(_L("Usb transfer error %d"), r); User::Leave(KErrGeneral); } } TPtrC8 data = iBulkInCswTd.Buffer(); r = iCsw.Decode(data); if (r != KErrNone) { __BOTPRINT(_L("Csw: Invalid")); DoResetRecovery(); User::Leave(KErrGeneral); } }
int test_multi() { ach_status_t r = ach_unlink(opt_channel_name); if( ! ach_status_match(r, ACH_MASK_OK | ACH_MASK_ENOENT) ) { fprintf(stderr, "ach_unlink failed\n: %s", ach_result_to_string(r)); return -1; } r = ach_create(opt_channel_name, 32ul, 64ul, NULL ); /* pid_t sub_pid[opt_n_sub]; */ /* pid_t pub_pid[opt_n_pub]; */ int i; /* create subscribers */ for( i = 0; i < opt_n_sub; i++ ) { pid_t p = fork(); if( p < 0 ) exit(-1); else if( 0 == p ) return subscriber(i); /* else sub_pid[i] = p; */ } /* create publishers */ for( i = 0; i < opt_n_pub; i++ ) { pid_t p = fork(); if( p < 0 ) exit(-1); else if( 0 == p ) return publisher(i); /* else pub_pid[i] = p; */ } /* wait */ for( i = 0; i < opt_n_sub+opt_n_pub; i++ ) { int s; pid_t pid = wait(&s); (void)pid; if( 0 != s ) return -1; } return 0; }
//============================================================================== int main() //============================================================================== { Ugv1::AgentMessenger publisher(BUS_URL); if( !publisher.isGood() ) { std::cout << "Error setting up messaging for publisher" << std::endl; return -1; } // the message example_t my_data; my_data.timestamp = 0; my_data.position[0] = 1; my_data.position[1] = 2; my_data.position[2] = 3; my_data.orientation[0] = 1; my_data.orientation[1] = 0; my_data.orientation[2] = 0; my_data.orientation[3] = 0; my_data.num_ranges = 15; my_data.ranges.resize(my_data.num_ranges); for(int i = 0; i < my_data.num_ranges; i++) { my_data.ranges[i] = i; } my_data.name = "example string"; my_data.enabled = true; publisher.publish(EXAMPLE_CHANNEL, &my_data); return 0; }
int main(int, char **) { boost::asio::ip::address address = boost::asio::ip::address::from_string("127.0.0.1"); const unsigned short port = 6379; boost::asio::io_service ioService; RedisAsyncClient publisher(ioService); RedisAsyncClient subscriber(ioService); publisher.asyncConnect(address, port, [&](bool status, const std::string &err) { if( !status ) { std::cerr << "Can't connect to to redis" << err << std::endl; } else { subscriber.asyncConnect(address, port, [&](bool status, const std::string &err) { if( !status ) { std::cerr << "Can't connect to to redis" << err << std::endl; } else { subscriber.subscribe(channelName, boost::bind(&subscribeHandler, boost::ref(ioService), _1), boost::bind(&publishHandler, boost::ref(publisher), _1)); } }); } }); ioService.run(); return 0; }
Transceiver::Transceiver(Partition& partition) : m_partition(partition), m_qos_query(qos_reader()), m_dispatcher(*this), m_topic(participant()), m_writer(publisher(), m_topic), m_echo_topic(participant()), m_reader(subscriber(), m_echo_topic), m_reader_condition(m_reader), m_reader_attachment(m_dispatcher, m_reader_condition), m_writer_thread(*this), m_reader_thread(*this), m_report_thread(*this), m_writer_active(false), m_reader_active(false), m_report_active(false), m_config_number(0) { // cout << "Transceiver::Transceiver(" << partition_id() << ")" << endl; }
void MainWindow::on_publishBtn_clicked() { Ugv1::AgentMessenger publisher( _pUi->urlEdit->text().toStdString() ); if( !publisher.isGood() ) { _errorInfo.setText("Error setting up publisher"); return; } // the message example_t my_data; my_data.timestamp = 0; my_data.position[0] = 1; my_data.position[1] = 2; my_data.position[2] = 3; my_data.orientation[0] = 1; my_data.orientation[1] = 0; my_data.orientation[2] = 0; my_data.orientation[3] = 0; my_data.num_ranges = 15; my_data.ranges.resize(my_data.num_ranges); for(int i = 0; i < my_data.num_ranges; i++) { my_data.ranges[i] = i; } my_data.name = "example string"; my_data.enabled = true; publisher.publish(_pUi->chnEdit->text().toStdString(), &my_data); }
int main () { zmq::context_t context(1); // Socket to talk to clients zmq::socket_t publisher (context, ZMQ_PUB); publisher.bind("tcp://*:5561"); // Socket to receive signals zmq::socket_t syncservice (context, ZMQ_REP); syncservice.bind("tcp://*:5562"); // Get synchronization from subscribers int subscribers = 0; while (subscribers < SUBSCRIBERS_EXPECTED) { // - wait for synchronization request s_recv (syncservice); // - send synchronization reply s_send (syncservice, ""); subscribers++; } // Now broadcast exactly 1M updates followed by END int update_nbr; for (update_nbr = 0; update_nbr < 1000000; update_nbr++) { s_send (publisher, "Rhubarb"); } s_send (publisher, "END"); s_sleep (1000); // Give 0MQ time to flush output return 0; }
int main () { zmq::context_t context(1); // Subscriber tells us when it's ready here zmq::socket_t sync(context, ZMQ_PULL); sync.bind("tcp://*:5564"); // We send updates via this socket zmq::socket_t publisher (context, ZMQ_PUB); publisher.bind("tcp://*:5565"); // Prevent publisher overflow from slow subscribers uint64_t hwm = 1; publisher.setsockopt( ZMQ_HWM, &hwm, sizeof (hwm)); // Specify swap space in bytes, this covers all subscribers uint64_t swap = 25000000; publisher.setsockopt( ZMQ_SWAP, &swap, sizeof (swap)); // Wait for synchronization request s_recv (sync); // Now broadcast exactly 10 updates with pause int update_nbr; for (update_nbr = 0; update_nbr < 10; update_nbr++) { std::ostringstream oss; oss << "Update "<< update_nbr ; s_send (publisher, oss.str()); sleep (1); } s_send (publisher, "END"); sleep (1); // Give 0MQ/2.0.x time to flush output return 0; }
void TestMetaManager::read() { QString album("Album: " + _meta->album()); QString artist("Artist: " + _meta->artist()); QString artwork("Artwork: " + _meta->artwork()); QString copyright("Copyright: " + _meta->copyright()); QString description("Description: " + _meta->description()); QString encoder("Encoder: " + _meta->encoder()); QString genre("Genre: " + _meta->genre()); QString id("ID: " + _meta->id()); QString language("Language: " + _meta->language()); QString number("Number: " + QString().number(_meta->number())); QString publisher("Publisher: " + _meta->publisher()); QString rating("Rating: " + _meta->rating()); QString setting("Setting: " + _meta->setting()); QString title("Title: " + _meta->title()); QString url("Url: " + _meta->url()); QString year("Year: " + QString().number(_meta->year())); ui->labelMeta->setText(album + "\n" + artist + "\n" + artwork + "\n" + copyright + "\n" + description + "\n" + encoder + "\n" + genre + "\n" + id + "\n" + language + "\n" + number + "\n" + publisher + "\n" + rating + "\n" + setting + "\n" + title + "\n" + url + "\n" + year + "\n"); }
int main() { char input[MAX] = "\0"; fgets(input, 21, stdin); int i=0; for(int count =0; count<strlen(input); count++) { if(input[count] >= '0' && input[count] <= '9') { integer[i+1] = input[count] - '0'; i++; } } i=4; while(input[i]!='-') { i++; } if(strlen(input)-1 == 17) { if(prefix(input) == 1) { if(control_number(input) == 1) { printf("1\n"); publisher(input, i); } } } return 0; }
int main(int argc, char* argv[]) { try { unsigned int size; double wait_after_connect = 0.0; std::size_t hwm; std::string server; boost::program_options::options_description description( "options" ); description.add_options() ( "help,h", "display help message; --help --verbose for more help" ) ( "publish", "use bind and publish (as opposed to connect and subscribe)" ) ( "connect", "use connect instead of bind" ) ( "bind", "use bind instead of connect" ) ( "request", "request/reply client" ) ( "reply", "request/reply server" ) ( "size,s", boost::program_options::value< unsigned int >( &size ), "packet size in bytes, in publish, request, or reply mode; if not present, data is line-based ascii" ) ( "buffer,b", boost::program_options::value< std::size_t >( &hwm )->default_value( 1024 ), "set buffer size in packets (high water mark in zmq)" ) ( "server", boost::program_options::value< std::string >( &server ), "in subscribe mode, republish the data on a socket, eg tcp:1234" ) ( "wait-after-connect,conwait", boost::program_options::value< double >( &wait_after_connect ), "time to wait, in seconds, after initial connection before attempting to read or write" ) ( "quiet-interrupt", "suppress error messages due to interrupt" ) ( "verbose,v", "more output" ); boost::program_options::variables_map vm; boost::program_options::store( boost::program_options::parse_command_line( argc, argv, description), vm ); boost::program_options::parsed_options parsed = boost::program_options::command_line_parser(argc, argv).options( description ).allow_unregistered().run(); boost::program_options::notify( vm ); if( vm.count( "help" ) ) { usage( description, !vm.count( "verbose" ) ); return 0; } const std::vector< std::string >& endpoints = boost::program_options::collect_unrecognized( parsed.options, boost::program_options::include_positional ); if( endpoints.empty() ) { std::cerr << "zero-cat: please provide at least one endpoint" << std::endl; return 1; } bool binary = vm.count( "size" ); quiet_interrupt = vm.count( "quiet-interrupt" ); comma::signal_flag is_shutdown; zmq::context_t context( 1 ); const bool is_request = vm.count( "request" ); const bool is_reply = vm.count( "reply" ); const bool is_publisher = bool( vm.count( "publish" ) ); if( is_request + is_reply + is_publisher > 1 ) { std::cerr << "zero-cat: expected only one of: --publisher, --request, --reply; got " << ( is_request + is_reply + is_publisher ) << std::endl; return 1; } if( is_request || is_reply ) { #ifdef WIN32 if( binary ) { _setmode( _fileno( stdin ), _O_BINARY ); _setmode( _fileno( stdout ), _O_BINARY ); } #endif zmq::socket_t socket( context, is_request ? ZMQ_REQ : ZMQ_REP ); #if ZMQ_VERSION_MAJOR == 2 socket.setsockopt( ZMQ_HWM, &hwm, sizeof( hwm ) ); #endif if( endpoints.size() != 1 ) { std::cerr << "zero-cat: request/reply server/client expected 1 endpoint, got " << endpoints.size() << ": " << comma::join( endpoints, ',' ) << std::endl; return 1; } if( is_request || vm.count( "connect" ) ) { socket.connect( &endpoints[0][0] ); } else if( is_reply || vm.count( "bind" ) ) { socket.bind( &endpoints[0][0] ); } if( is_request ) { std::string buffer; if( binary ) { buffer.resize( size ); } while( !is_shutdown && std::cin.good() ) { if( binary ) { std::cin.read( &buffer[0], size ); int count = std::cin.gcount(); if( count == 0 ) { break; } if( count < int( size ) ) { std::cerr << "zero-cat: expected " << size << " byte(s), got: " << count << std::endl; return 1; } } else { std::getline( std::cin, buffer ); if( buffer.empty() ) { break; } buffer += endl; } zmq::message_t request( buffer.size() ); ::memcpy( ( void * )request.data(), &buffer[0], buffer.size() ); #if ZMQ_VERSION_MAJOR == 2 if( !socket.send( request ) ) { std::cerr << "zero-cat: failed to send " << buffer.size() << " bytes; zmq errno: EAGAIN" << std::endl; return 1; } #else // ZMQ_VERSION_MAJOR == 2 if( !socket.send( &buffer[0], buffer.size() ) ) { std::cerr << "zero-cat: failed to send " << buffer.size() << " bytes; zmq errno: EAGAIN" << std::endl; return 1; } #endif // ZMQ_VERSION_MAJOR == 2 zmq::message_t reply; if( !socket.recv( &reply ) ) { break; } std::cout.write( reinterpret_cast< const char* >( reply.data() ), reply.size() ); if( binary ) { std::cout.flush(); } } } else { std::string buffer; if( binary ) { buffer.resize( size ); } while( !is_shutdown && std::cin.good() ) { zmq::message_t request; if( !socket.recv( &request ) ) { break; } std::cout.write( reinterpret_cast< const char* >( request.data() ), request.size() ); if( binary ) { std::cout.flush(); } if( binary ) { std::cin.read( &buffer[0], size ); int count = std::cin.gcount(); if( count == 0 ) { break; } if( count < int( size ) ) { std::cerr << "zero-cat: expected " << size << " byte(s), got: " << count << std::endl; return 1; } } else { std::getline( std::cin, buffer ); if( buffer.empty() ) { break; } buffer += endl; } zmq::message_t reply( buffer.size() ); ::memcpy( ( void * )reply.data(), &buffer[0], buffer.size() ); #if ZMQ_VERSION_MAJOR == 2 if( !socket.send( reply ) ) { std::cerr << "zero-cat: failed to send " << buffer.size() << " bytes; zmq errno: EAGAIN" << std::endl; return 1; } #else // ZMQ_VERSION_MAJOR == 2 if( !socket.send( &buffer[0], buffer.size() ) ) { std::cerr << "zero-cat: failed to send " << buffer.size() << " bytes; zmq errno: EAGAIN" << std::endl; return 1; } #endif // ZMQ_VERSION_MAJOR == 2 } } return 0; } int mode = is_publisher ? ZMQ_PUB : ZMQ_SUB; zmq::socket_t socket( context, mode ); #ifdef WIN32 if( is_publisher && binary ) { _setmode( _fileno( stdin ), _O_BINARY ); } #endif // Although the documentation says that HWM is supported in ZMQ4, the // code shows that if the sock opt is HWM an exception will be thrown. #if ZMQ_VERSION_MAJOR == 2 socket.setsockopt( ZMQ_HWM, &hwm, sizeof( hwm ) ); #endif if( is_publisher ) { bool output_to_stdout = false; for( unsigned int i = 0; i < endpoints.size(); i++ ) { if( endpoints[i] == "-" ) { output_to_stdout = true; } else if( vm.count( "connect" ) ) { socket.connect( endpoints[i].c_str() ); } else { socket.bind( &endpoints[i][0] ); } } // we convert to milliseconds as converting to second floors the number so 0.99 becomes 0 if( wait_after_connect > 0 ) { boost::this_thread::sleep(boost::posix_time::milliseconds(wait_after_connect * 1000.0)); } std::string buffer; if( binary ) { buffer.resize( size ); } while( !is_shutdown && std::cin.good() && !std::cin.eof() && !std::cin.bad() ) { if( binary ) { std::cin.read( &buffer[0], buffer.size() ); int count = std::cin.gcount(); if( count <= 0 ) { break; } buffer.resize( std::size_t( count ) ); } else { std::getline( std::cin, buffer ); if( !is_shutdown && std::cin.good() && !std::cin.eof() && !std::cin.bad() ) { buffer += endl; } } if( buffer.empty() ) { break; } #if ZMQ_VERSION_MAJOR == 2 zmq::message_t message( buffer.size() ); ::memcpy( ( void * )message.data(), &buffer[0], buffer.size() ); if( !socket.send( message ) ) { std::cerr << "zero-cat: failed to send " << buffer.size() << " bytes; zmq errno: EAGAIN" << std::endl; return 1; } #else // ZMQ_VERSION_MAJOR == 2 if( !socket.send( &buffer[0], buffer.size() ) ) { std::cerr << "zero-cat: failed to send " << buffer.size() << " bytes; zmq errno: EAGAIN" << std::endl; return 1; } #endif // ZMQ_VERSION_MAJOR == 2 if( !output_to_stdout ) { continue; } std::cout.write( &buffer[0], buffer.size() ); if( binary ) { std::cout.flush(); } } } else { for( unsigned int i = 0; i < endpoints.size(); i++ ) { if( vm.count( "bind" ) ) { socket.bind( endpoints[i].c_str() ); } else { socket.connect( endpoints[i].c_str() ); } } socket.setsockopt( ZMQ_SUBSCRIBE, "", 0 ); if( wait_after_connect > 0 ) { boost::this_thread::sleep( boost::posix_time::milliseconds( wait_after_connect * 1000.0 ) ); } if( vm.count( "server" ) ) { comma::io::publisher publisher( server, comma::io::mode::binary, true, false ); while( !is_shutdown ) { zmq::message_t message; socket.recv( &message ); publisher.write( reinterpret_cast< const char* >( message.data() ), message.size() ); } } else { while( !is_shutdown && std::cout.good() ) { zmq::message_t message; socket.recv( &message ); std::cout.write( reinterpret_cast< const char* >( message.data() ), message.size() ); if( binary ) { std::cout.flush(); } } } } return 0; } catch ( zmq::error_t& e ) { if( !quiet_interrupt || e.num() != EINTR ) { std::cerr << argv[0] << ": zeromq error: (" << e.num() << ") " << e.what() << std::endl; } } catch ( std::exception& e ) { std::cerr << argv[0] << ": " << e.what() << std::endl; } catch ( ... ) { std::cerr << argv[0] << ": unknown exception" << std::endl; } return 1; }