Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- server.c:
- #include <assert.h>
- #include <stdio.h>
- #include "nanomsg/nn.h"
- #include "nanomsg/reqrep.h"
- #include <nanomsg/utils/thread.h>
- #include <nanomsg/utils/thread.c>
- #include <nanomsg/utils/atomic.h>
- #include <nanomsg/utils/atomic.c>
- #include <nanomsg/utils/err.h>
- #include <nanomsg/utils/err.c>
- #define ADDRESS_REQ "tcp://127.0.0.1:4444"
- #define ADDRESS_REP "tcp://127.0.0.1:4445"
- #define NO_THREADS 8
- struct nn_thread tid[NO_THREADS];
- static int workers = 0;
- void device(void * arg)
- {
- int rc;
- int device_req;
- int device_rep;
- /* Initialise the device sockets */
- device_req = nn_socket(AF_SP_RAW, NN_REQ);
- nn_bind(device_req, ADDRESS_REQ);
- device_rep = nn_socket(AF_SP_RAW, NN_REP);
- nn_bind(device_rep, ADDRESS_REP);
- /* Run the device */
- rc = nn_device(device_req, device_rep);
- /* This means nn_device loop exited either by an error or by calling nn_term() */
- ASSERT(rc < 0 && nn_errno() == ETERM);
- /* Clean up */
- nn_close(device_req);
- nn_close(device_rep);
- }
- void worker(void * arg)
- {
- int sock;
- int bind;
- int worker = workers++;
- sock = nn_socket(AF_SP, NN_REP);
- bind = nn_bind(sock, ADDRESS_REP);
- assert(bind >= 0);
- printf("Server: %u, server_loop\n", worker);
- while(1) {
- char * buf = NULL;
- int bytes = nn_recv(sock, &buf, NN_MSG, 0);
- if (bytes <= 0) {
- break;
- }
- printf("Server: %u, received: %s\n", worker, buf);
- nn_send(sock, ADDRESS_REP, sizeof(ADDRESS_REP), 0);
- nn_freemsg(buf);
- }
- nn_shutdown(sock, bind);
- nn_close(sock);
- }
- int main(int argc, const char * argv[])
- {
- int i = 1;
- nn_thread_init(&tid[0], &device, NULL);
- for(i = 1; i < NO_THREADS; i++) {
- nn_thread_init(&tid[i], &worker, NULL);
- }
- while(1) {
- Sleep(1000);
- }
- return 0;
- }
- client.c:
- #include <assert.h>
- #include <stdio.h>
- #include <string.h>
- #include "nanomsg/nn.h"
- #include "nanomsg/reqrep.h"
- #define ADDRESS_REQ "tcp://127.0.0.1:4445"
- int main(int argc, const char * argv[])
- {
- const char * name = NULL;
- int sock;
- int conn;
- if (argc < 2) {
- printf("client [name]\n");
- return 1;
- }
- name = *(argv + 1);
- sock = nn_socket(AF_SP, NN_REQ);
- conn = nn_connect(sock, ADDRESS_REQ);
- printf("client %s\n", name);
- nn_send(sock, name, strlen(name) + 1, 0);
- while(1) {
- char * buf = NULL;
- int bytes = nn_recv(sock, &buf, NN_MSG, 0);
- if (bytes > 0) {
- printf("received: %s\n", buf);
- nn_freemsg(buf);
- break;
- }
- }
- nn_shutdown(sock, conn);
- nn_close(sock);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement