// Compiles with Visual Studio 2008 for Windows // Minimal C ZMQ Server example // Properties -> Linker -> Input -> Additional dependencies "libzmq.lib" // Properties -> Linker -> Input -> Additional dependencies "ws2_32.lib" #include <stdio.h> #include <string.h> // for strstr() #include "zmq.h" #include <winsock2.h> #define WS_VER 0x0202 #define DEFAULT_PORT "5001" int main () { int retval, done = 0; void *ctx, *s; zmq_msg_t query, reply; const char *query_string, *reply_string = "C++ OK"; WSADATA wsaData; // Initialise Windows Sockets WSAStartup( WS_VER, &wsaData ); printf( "Initialise ZMQ context \n"); // Initialise ZMQ context, requesting a single application thread and a single I/O thread ctx = zmq_init(1); if( ctx == 0 ) { printf( "Error zmq_init: '%s'\n", zmq_strerror(errno) ); return 0; } while(1) { // Create a ZMQ_REP socket to receive requests and send replies s = zmq_socket( ctx, ZMQ_REP ); if( s == 0) { printf( "Error zmq_socket: '%d'\n", zmq_strerror(errno) ); break; } // Bind to the TCP transport and port 5555 on the 'lo' interface retval = zmq_bind( s, "tcp://*:5555" ); if( retval != 0 ) { printf( "zmq_bind errno: %d\n", zmq_errno ); printf( "Error zmq_bind: '%s'\n", zmq_strerror(errno) ); break; } while( done == 0 ) { // Allocate an empty message to receive a query into retval = zmq_msg_init(&query); if( retval != 0 ) { printf( "Error zmq_msg_init: '%s'\n", zmq_strerror(errno) ); break; } // printf( "Waiting for message... \n"); // Receive a message, blocks until one is available retval = zmq_recv( s, &query, 0 ); if( retval != 0 ) { printf( "Error zmq_recv: '%s'\n", zmq_strerror(errno) ); break; } // Process the query query_string = (const char *)zmq_msg_data(&query); printf("Received query: '%s'\n", query_string); if( strstr( query_string, "END SERVER" ) != 0 ) { done = 1; }; retval = zmq_msg_close( &query ); if( retval != 0 ) { printf( "Error zmq_msg_close: '%s'\n", zmq_strerror(errno) ); break; } //================= // Allocate a response message and fill in an example response retval = zmq_msg_init_size( &reply, strlen(reply_string)+1 ); if( retval != 0 ) { printf( "Error zmq_msg_init_size: '%s'\n", zmq_strerror(errno) ); break; } memcpy( zmq_msg_data(&reply), reply_string, strlen(reply_string)+1 ); // Return response retval = zmq_send( s, &reply, 0 ); if( retval != 0 ) { printf( "Error zmq_send: '%s'\n", zmq_strerror(errno) ); break; } // Free message memory zmq_msg_close(&reply); } // While not done break; } // While no error // Close connection if( s != 0 ) { printf( "Close connection \n"); retval = zmq_close(s); if( retval != 0 ) { printf( "Error zmq_close: '%s'\n", zmq_strerror(errno) ); } } // Release library resources retval = zmq_term(ctx); // Release WinSock WSACleanup(); printf( "All Done \n" ); return 0; } |