Created
April 15, 2013 08:00
-
-
Save Mononofu/5386488 to your computer and use it in GitHub Desktop.
Networked multi-user chat with auto-reconnect.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "zmq.hpp" | |
#include <string> | |
#include <iostream> | |
#include <pthread.h> | |
using namespace std; | |
void *msg_routine(void *arg) { | |
zmq::socket_t *message_source = (zmq::socket_t *) arg; | |
while(true) { | |
// Get the reply. | |
zmq::message_t reply; | |
message_source->recv (&reply); | |
std::cout << "- " << (char *) reply.data() << std::endl; | |
} | |
} | |
int main () | |
{ | |
// Prepare our context and socket | |
zmq::context_t context (1); | |
std::cout << "Connecting to hello world server…" << std::endl; | |
zmq::socket_t message_source (context, ZMQ_SUB); | |
message_source.connect ("tcp://127.0.0.1:5555"); | |
message_source.setsockopt(ZMQ_SUBSCRIBE, "", 0); | |
zmq::socket_t message_sink (context, ZMQ_PUB); | |
message_sink.connect ("tcp://127.0.0.1:5556"); | |
pthread_t msg_reader; | |
pthread_create (&msg_reader, NULL, msg_routine, (void *) &message_source); | |
string line; | |
while(true) { | |
getline(cin, line); | |
if(cin.eof()) | |
break; | |
zmq::message_t request (line.length() + 1); | |
memcpy ((void *) request.data (), line.c_str(), line.length() + 1); | |
message_sink.send (request); | |
} | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <unistd.h> | |
#include <cassert> | |
#include <string> | |
#include <iostream> | |
#include "zmq.hpp" | |
int main () | |
{ | |
// Prepare our context and sockets | |
zmq::context_t context (1); | |
zmq::socket_t message_source (context, ZMQ_PUB); | |
message_source.bind ("tcp://*:5555"); | |
zmq::socket_t message_sink (context, ZMQ_SUB); | |
message_sink.bind ("tcp://*:5556"); | |
message_sink.setsockopt(ZMQ_SUBSCRIBE, "", 0); | |
while (true) { | |
// Wait for next request from client | |
zmq::message_t request; | |
message_sink.recv (&request); | |
std::cout << "Received msg: [" << (char*) request.data() << "]" << std::endl; | |
// Send reply back to client | |
zmq::message_t reply (request.size() + 1); | |
memcpy ((void *) reply.data (), request.data(), request.size() + 1); | |
message_source.send (reply); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment