コード例 #1
0
ファイル: zerocopy.c プロジェクト: prenaux/nanomsg
void test_allocmsg_reqrep ()
{
    int rc;
    int req;
    void *p;
    struct nn_iovec iov;
    struct nn_msghdr hdr;

    /*  Try to create an oversized message. */
    p = nn_allocmsg (-1, 0);
    nn_assert (!p && nn_errno () == ENOMEM);
    p = nn_allocmsg (-1000, 0);
    nn_assert (!p && nn_errno () == ENOMEM);

    /*  Try to create a message of unknown type. */
    p = nn_allocmsg (100, 333);
    nn_assert (!p && nn_errno () == EINVAL);

    /*  Create a socket. */
    req = test_socket (AF_SP_RAW, NN_REQ);

    /*  Make send fail and check whether the zero-copy buffer is left alone
        rather than deallocated. */
    p = nn_allocmsg (100, 0);
    nn_assert (p);
    rc = nn_send (req, &p, NN_MSG, NN_DONTWAIT);
    nn_assert (rc < 0);
    errno_assert (nn_errno () == EAGAIN);
    memset (p, 0, 100);
    rc = nn_freemsg (p);
    errno_assert (rc == 0);

    /*  Same thing with nn_sendmsg(). */
    p = nn_allocmsg (100, 0);
    nn_assert (p);
    iov.iov_base = &p;
    iov.iov_len = NN_MSG;
    memset (&hdr, 0, sizeof (hdr));
    hdr.msg_iov = &iov;
    hdr.msg_iovlen = 1;
    nn_sendmsg (req, &hdr, NN_DONTWAIT);
    errno_assert (nn_errno () == EAGAIN);
    memset (p, 0, 100);
    rc = nn_freemsg (p);
    errno_assert (rc == 0);

    /*  Clean up. */
    test_close (req);
}
コード例 #2
0
ファイル: test_nnxx_ext.cpp プロジェクト: Bigpet/nanomsgxx
int main() {
  struct nn_msgctl ctl1;
  struct nn_msgctl ctl2;
  int s1 = nn_socket (AF_SP_RAW, NN_REP);
  int s2 = nn_socket (AF_SP, NN_REQ);
  int s3 = nn_socket (AF_SP, NN_REQ);
  void *buf1 = nullptr;
  void *buf2 = nullptr;

  nnxx_assert (s1 >= 0);
  nnxx_assert (s2 >= 0);

  /*  Connecting sockets. */
  nnxx_assert (nn_bind (s1, "inproc://test") >= 0);
  nnxx_assert (nn_connect (s2, "inproc://test") >= 0);
  nnxx_assert (nn_connect (s3, "inproc://test") >= 0);

  /*  Sending requests. */
  nnxx_assert (nn_send (s2, "Hello World! (1)", 16, 0) == 16);
  nnxx_assert (nn_send (s3, "Hello World! (2)", 16, 0) == 16);

  /*  Recieving requests. */
  nnxx_assert (nn_recvfrom (s1, &buf1, NN_MSG, 0, &ctl1) == 16);
  nnxx_assert (nn_recvfrom (s1, &buf2, NN_MSG, 0, &ctl2) == 16);

  /*  Making sure we have the correct data. */
  nnxx_assert (memcmp (buf1, "Hello World! (1)", 16) == 0);
  nnxx_assert (memcmp (buf2, "Hello World! (2)", 16) == 0);

  /*  Sending responses back in reverse order. */
  nnxx_assert (nn_sendto (s1, &buf2, NN_MSG, 0, &ctl2) == 16);
  nnxx_assert (nn_sendto (s1, &buf1, NN_MSG, 0, &ctl1) == 16);

  /*  Recieving responses. */
  nnxx_assert (nn_recv (s2, &buf1, NN_MSG, 0) == 16);
  nnxx_assert (nn_recv (s3, &buf2, NN_MSG, 0) == 16);

  /*  Making sure the clients got the right responses. */
  nnxx_assert (memcmp (buf1, "Hello World! (1)", 16) == 0);
  nnxx_assert (memcmp (buf2, "Hello World! (2)", 16) == 0);

  /*  Releasing resources. */
  nn_freemsg (buf2);
  nn_freemsg (buf1);
  nn_close (s2);
  nn_close (s1);
  return nnxx::unittest::result;
}
コード例 #3
0
ファイル: DebuggerIPCServer.cpp プロジェクト: pfpsim/PFPSim
PFPSimDebugger::DebugMsg* DebuggerIPCServer::recv() {
  struct nn_pollfd pfd;
  pfd.fd     = socket;
  pfd.events = NN_POLLIN;

  auto rc = nn_poll(&pfd, 1, 100);
  if (rc == 0) {
    return nullptr;
  }

  if (rc == -1) {
    // TODO(gordon)
    printf("Error!");
    exit(1);
  }

  if (pfd.revents & NN_POLLIN) {
    char *buf;
    int bytes = nn_recv(socket, &buf, NN_MSG, 0);
    if (bytes != -1) {
      std::string message_string(buf, bytes);
      nn_freemsg(buf);

      PFPSimDebugger::DebugMsg *message = new PFPSimDebugger::DebugMsg();
      message->ParseFromString(message_string);
      return message;
    } else {
      return nullptr;
    }
  } else {
    return nullptr;
  }
}
コード例 #4
0
int ftw_socket_inbox_recv(struct ftw_incoming_request *incoming, json_t **json_msg, size_t flags,
    int64 *err_line, int64 *err_column, int64 *err_position, LStrHandle err_source, LStrHandle err_hint)
{
    json_error_t err;
    int rc;

    /*  Preconditions expected of LabVIEW. */
    ftw_assert(incoming && incoming->msg_ptr && incoming->inbox && json_msg);

    /*  Notify async receive thread that it can pipeline the next message into the LVEvent. */
    nn_sem_post(&incoming->inbox->msg_acknowledged);

    *json_msg = json_loadb(incoming->msg_ptr, incoming->msg_len, flags, &err);

    rc = nn_freemsg(incoming->msg_ptr);
    ftw_assert(rc == 0);

    /*  Invalid JSON in the buffer is an error condition indicated by NULL. */
    if (*json_msg == NULL) {
        *err_line = err.line;
        *err_column = err.column;
        *err_position = err.position;
        ftw_support_CStr_to_LStrHandle(&err_source, err.source, sizeof(err.source));
        ftw_support_CStr_to_LStrHandle(&err_hint, err.text, sizeof(err.text));
        *json_msg = json_object();
    }

    return rc;
}
コード例 #5
0
ファイル: bus.c プロジェクト: marvinyane/demoCode
int node (const int argc, const char **argv)
{
    int sock = nn_socket (AF_SP, NN_BUS);
    assert (sock >= 0);
    assert (nn_bind (sock, argv[2]) >= 0);
    sleep (1); // wait for connections
    if (argc >= 3)
    {
        int x=3;
        for(x; x<argc; x++)
            assert (nn_connect (sock, argv[x]) >= 0);
    }
    sleep (1); // wait for connections
    int to = 100;
    assert (nn_setsockopt (sock, NN_SOL_SOCKET, NN_RCVTIMEO, &to, sizeof (to)) >= 0);
    // SEND
    int sz_n = strlen(argv[1]) + 1; // '\0' too
    printf ("%s: SENDING '%s' ONTO BUS\n", argv[1], argv[1]);
    int send = nn_send (sock, argv[1], sz_n, 0);
    assert (send == sz_n);
    while (1)
    {
        // RECV
        char *buf = NULL;
        int recv = nn_recv (sock, &buf, NN_MSG, 0);
        if (recv >= 0)
        {
            printf ("%s: RECEIVED '%s' FROM BUS\n", argv[1], buf);
            nn_freemsg (buf);
        }
    }
    return nn_shutdown (sock, 0);
}
コード例 #6
0
ファイル: relays777.c プロジェクト: satindergrewal/btcd
char *nn_loadbalanced(uint8_t *data,int32_t len)
{
    char *msg,*jsonstr = 0;
    int32_t sendlen,i,lbsock,recvlen = 0;
    if ( (lbsock= RELAYS.lbclient) < 0 )
        return(clonestr("{\"error\":\"invalid load balanced socket\"}"));
    for (i=0; i<10; i++)
        if ( (nn_socket_status(lbsock,1) & NN_POLLOUT) != 0 )
            break;
    if ( Debuglevel > 2 )
        printf("sock.%d NN_LBSEND.(%s)\n",lbsock,data);
    //fprintf(stderr,"send to network\n");
    if ( (sendlen= nn_send(lbsock,data,len,0)) == len )
    {
        for (i=0; i<10; i++)
            if ( (nn_socket_status(lbsock,1) & NN_POLLIN) != 0 )
                break;
        if ( (recvlen= nn_recv(lbsock,&msg,NN_MSG,0)) > 0 )
        {
            if ( Debuglevel > 2 )
                printf("LBRECV.(%s)\n",msg);
            jsonstr = clonestr((char *)msg);
            nn_freemsg(msg);
        }
        else
        {
            printf("nn_loadbalanced got recvlen.%d %s\n",recvlen,nn_errstr());
            jsonstr = clonestr("{\"error\":\"lb recv error, probably timeout\"}");
        }
    } else printf("got sendlen.%d instead of %d %s\n",sendlen,len,nn_errstr()), jsonstr = clonestr("{\"error\":\"lb send error\"}");
    return(jsonstr);
}
コード例 #7
0
ファイル: ipc_stress.c プロジェクト: 4ker/nanomsg
static void server(NN_UNUSED void *arg)
{
    int bytes;
    int count;
    int sock = nn_socket(AF_SP, NN_PULL);
    int res[TEST_LOOPS];
    nn_assert(sock >= 0);
    nn_assert(nn_bind(sock, SOCKET_ADDRESS) >= 0);
    count = THREAD_COUNT * TEST_LOOPS;
    memset(res, 0, sizeof (res));
    while (count > 0)
    {
        char *buf = NULL;
        int tid;
        int num;
        bytes = nn_recv(sock, &buf, NN_MSG, 0);
        nn_assert(bytes >= 0);
        nn_assert(bytes >= 2);
        nn_assert(buf[0] >= 'A' && buf[0] <= 'Z');
        nn_assert(buf[1] >= 'a' && buf[0] <= 'z');
        tid = buf[0]-'A';
        num = buf[1]-'a';
        nn_assert(tid < THREAD_COUNT);
        nn_assert(res[tid] == num);
        res[tid]=num+1;
        nn_freemsg(buf);
        count--;
    }
    nn_close(sock);
}
コード例 #8
0
ファイル: test_network.cpp プロジェクト: fionser/MDLHELib
void receive_ctxt(int socket, const FHEPubKey &pk,
                  std::vector<Ctxt> &ctxts) {
    std::stringstream sstream;
    MDL::Timer timer;
    char *buf;
    nn_recv(socket, &buf, NN_MSG, 0); // recv lens
    nn_send(socket, NULL, 0, 0); // send ok
    MDL::net::msg_header *hdr = (MDL::net::msg_header *)buf;

    std::vector<size_t> lens(hdr->msg_ele_sze,
                             hdr->msg_ele_sze + hdr->msg_ele_nr);
    printf("vec size %zd\n", lens.size());
    timer.start();
    struct nn_msghdr nn_hdr;
    MDL::net::make_nn_header(&nn_hdr, lens);
    printf("%zd\n", nn_hdr.msg_iovlen);
    nn_recvmsg(socket, &nn_hdr, 0); // recv data
    timer.end();

    Ctxt c(pk);
    for (size_t i = 0; i < nn_hdr.msg_iovlen; i++) {
        sstream.str((char *)nn_hdr.msg_iov[i].iov_base);
        sstream >> c;
        ctxts.push_back(c);
    }
    nn_freemsg(buf);
    nn_send(socket, NULL, 0, 0);
    printf("receive %zd ciphers %fs\n", ctxts.size(), timer.second());
}
コード例 #9
0
ファイル: reqrep.c プロジェクト: hamidreza-s/myCode
/* --- server --- */
int node0(const char *url) {

  int sz_date = strlen(DATE) + 1;
  int sock = nn_socket(AF_SP, NN_REP);

  assert(sock >= 0);
  assert(nn_bind(sock, url) >= 0);

  while(1) {
    char *buf = NULL;
    int bytes = nn_recv(sock, &buf, NN_MSG, 0);
    assert(bytes >= 0);
    if(strncmp(DATE, buf, sz_date) == 0) {
      printf("NODE0: RECEIVED DATE REQUEST\n");
      char *st_date = date();
      int sz_date = strlen(st_date) + 1;
      printf("NODE0: SENDING DATE %s\n", st_date);
      bytes = nn_send(sock, st_date, sz_date, 0);
      assert(bytes == sz_date);
    }
    nn_freemsg(buf);
  }

  return nn_shutdown(sock, 0);
}
コード例 #10
0
ファイル: relays777.c プロジェクト: satindergrewal/btcd
void serverloop(void *_args)
{
    int32_t n;
#ifdef INSIDE_MGW
    int32_t make_MGWbus(uint16_t port,char *bindaddr,char serverips[MAX_MGWSERVERS][64],int32_t n);
    int32_t mgw_processbus(char *retbuf,char *jsonstr,cJSON *json);
    int32_t len; char retbuf[8192],*jsonstr; cJSON *json;
    if ( SUPERNET.gatewayid >= 0 )
        MGW.all.socks.both.bus = make_MGWbus(MGW.port,SUPERNET.myipaddr,MGW.serverips,SUPERNET.numgateways+1*0);
#endif
    sleep(3);
    printf("start serverloop\n");
    while ( OS_getppid() == SUPERNET.ppid )
    {
#ifdef INSIDE_MGW
        if ( SUPERNET.gatewayid >= 0 && (len= nn_recv(MGW.all.socks.both.bus,&jsonstr,NN_MSG,0)) > 0 )
        {
            if ( (json= cJSON_Parse(jsonstr)) != 0 )
            {
                mgw_processbus(retbuf,jsonstr,json);
                free_json(json);
            }
            //printf("MGW bus recv.%d json.%p\n",len,json);
            nn_freemsg(jsonstr);
        }
#endif
        n = busdata_poll();
        if ( n == 0 && SUPERNET.APISLEEP > 0 )
            msleep(SUPERNET.APISLEEP);
    }
    printf("finished serverloop\n");
}
コード例 #11
0
ファイル: nano_socket.cpp プロジェクト: variar/kluster
    NanoMessage NanoSocket::Recv() throw()
    {
      char *buf = NULL;
      int size = nn_recv (m_socket, &buf, NN_MSG, 0);
      if (size < 0)
      {
        throw NanoException{};
      }

      std::stringstream compressed;
      compressed.write(buf, size);
      nn_freemsg (buf);

      ios::filtering_streambuf<ios::input> decompressor;
      decompressor.push(ios::zlib_decompressor());
      decompressor.push(compressed);

      std::stringstream decompressed;
      ios::copy(decompressor, decompressed);

      NanoMessage nm = NanoMessage::LoadMessage(decompressed.str());
      std::cout << "Socket " << m_socket << ": "
        << "got message type " << nm.header.type << std::endl;
      return nm;
    }
コード例 #12
0
ファイル: nn.hpp プロジェクト: 4ker/cppnanomsg
 inline int freemsg (void *msg)
 {
     int rc = nn_freemsg (msg);
     if (nn_slow (rc != 0))
         throw nn::exception ();
     return rc;
 }
コード例 #13
0
ファイル: zmq.c プロジェクト: Droppe/nanomsg
int zmq_msg_close (zmq_msg_t *msg)
{
    struct nn_zmqmsg *zmqmsg;

    zmqmsg = (struct nn_zmqmsg*) msg;
    if (!zmqmsg->data)
        return 0;
    return nn_freemsg (zmqmsg->data);
}
コード例 #14
0
ファイル: pair.c プロジェクト: shitfSign/nanomsg-tutorial
int recv_name(int sock, const char *name)
{
        char *buf = NULL;
        int result = nn_recv(sock, &buf, NN_MSG, 0);
        if (result > 0)
        {
                printf("%s: RECEIVED \"%s\"\n", name, buf);
                nn_freemsg(buf);
        }
        return result;
}
コード例 #15
0
ファイル: test_network.cpp プロジェクト: fionser/MDLHELib
void receive_pk(int socket, FHEPubKey &pk) {
    char *buf;
    int read;
    if ((read = nn_recv(socket, &buf, NN_MSG, 0)) < 0) {
        printf("receive pk error %s\n", nn_strerror(errno));
        exit(-1);
    }
    std::stringstream sstream;
    sstream.str(buf);
    sstream >> pk;
    nn_freemsg(buf);
}
コード例 #16
0
ファイル: NanoLibrary.c プロジェクト: tempbottle/jnano
JNIEXPORT jstring JNICALL Java_org_nanomsg_NanoLibrary_nn_1recvstr(JNIEnv* env,
                                                             jobject obj,
                                                             jint socket,
                                                             jint flags)
{
	void *buf;
	int ret = nn_recv(socket, &buf, NN_MSG, flags);
	if (ret < 0) return 0;
	jstring retst = (*env)->NewStringUTF(env, buf);
	nn_freemsg(buf);
	return retst;
}
コード例 #17
0
ファイル: pipeline.c プロジェクト: hamidreza-s/myCode
/* --- server --- */
int node0(const char *url) {
  int sock = nn_socket(AF_SP, NN_PULL);
  assert (sock >= 0);
  assert (nn_bind(sock, url) >= 0);
  while(1) {
      char *buf = NULL;
      int bytes = nn_recv (sock, &buf, NN_MSG, 0);
      assert(bytes >= 0);
      printf("NODE0: RECEIVED \"%s\"\n", buf);
      nn_freemsg (buf);
    }
}
コード例 #18
0
static void ftw_subscriber_async_recv_thread(void *arg)
{
    LStrHandle msg_sent_to_lv;
    struct ftw_socket *self;
    void *recv_buf;
    MgErr lv_err;
    int socket_err;
    int rc;

    ftw_assert(arg);

    /*  Create local pointer to arguments and notify launching process this thread is constructed. */
    self = ((struct ftw_socket *) arg);
    nn_sem_post(&self->async_recv_ready);

    lv_err = mgNoErr;
    socket_err = 0;

    /*  This broker relays messages from the nanomsg socket into the LabVIEW incoming message queue. */
    while (!lv_err && !socket_err) {

        rc = nn_recv(self->id, &recv_buf, NN_MSG, 0);

        if (rc < 0) {
            socket_err = ((errno == ETIMEDOUT || errno == EAGAIN) ? 0 : errno);
            continue;
        }

        msg_sent_to_lv = (LStrHandle)DSNewHandle(rc);
        lv_err = ftw_support_buffer_to_LStrHandle(&msg_sent_to_lv, recv_buf, rc);
        if (lv_err)
            continue;

        /*  On the LabVIEW side, the handler is a an event registration, meaning
            LabVIEW will not effectively apply backpressure to the Publisher socket.
            For this reason, care must be taken that the Subscriber keep up with
            the Publisher, yet this consideration has long-existed for the LabVIEW
            developer (since, LV-native primitives will likewise cause a memory leak,
            when Event Registrations are allowed to grow without bound). */
        lv_err = PostLVUserEvent(self->incoming_msg_notifier_event, &msg_sent_to_lv);
        if (lv_err)
            continue;

        lv_err = DSDisposeHandle (msg_sent_to_lv);
        rc = nn_freemsg(recv_buf);
        if (rc) {
            socket_err = errno;
            continue;
        }
    }

    return;
}
コード例 #19
0
static void send_start_message(OUTPROCESS_HANDLE_DATA* handleData)
{
    int32_t startMessageSize = 0;
    void * startmessage = construct_start_message(handleData, &startMessageSize);
    /*Codes_SRS_OUTPROCESS_MODULE_17_019: [ This function shall send a Start Message on the control channel. ]*/
    int nBytes = nn_really_send(handleData->control_socket, &startmessage, NN_MSG, 0);
    if (nBytes != startMessageSize)
    {
        /*Codes_SRS_OUTPROCESS_MODULE_17_021: [ This function shall free any resources created. ]*/
        LogError("unable to send start message [%p]", startmessage);
        nn_freemsg(startmessage);
    }
}
コード例 #20
0
ファイル: NanoLibrary.c プロジェクト: tempbottle/jnano
JNIEXPORT jbyteArray JNICALL Java_org_nanomsg_NanoLibrary_nn_1recvbyte(JNIEnv* env,
                                                             jobject obj,
                                                             jint socket,
                                                             jint flags)
{
	void *buf;
	int ret = nn_recv(socket, &buf, NN_MSG, flags);
	if (ret < 0) return 0;
    jbyteArray result = (*env)->NewByteArray(env, ret);
    (*env)->SetByteArrayRegion(env, result, 0, ret, (const jbyte*) buf);
	nn_freemsg(buf);
	return result;
}
コード例 #21
0
ファイル: bus.c プロジェクト: GrayTShirt/nano-tutorial
int node (const int argc, const char **argv)
{
	int sock    = nn_socket (AF_SP, NN_BUS);
	int sock_fd, efd, nfds;
	struct epoll_event event, events[MAX_EVENTS];
	size_t sz = sizeof(sock_fd);
	nn_getsockopt(sock, NN_SOL_SOCKET, NN_RCVFD, &sock_fd, &sz);
	assert(sock >= 0);
	assert(nn_bind (sock, argv[2]) >= 0);
	sleep (1); // wait for connections
	if (argc >= 3) {
		int x;
		for(x = 3; x < argc; x++)
			assert(nn_connect(sock, argv[x]) >= 0);
	}
	efd = epoll_create(MAX_EVENTS);
	assert(efd != -1);

	event.data.fd = sock_fd;
	event.events  = EPOLLIN;
	assert(epoll_ctl(efd, EPOLL_CTL_ADD, sock_fd, &event) != -1);

	// wait for connections
	sleep(1);
	int to = 100;
	assert(nn_setsockopt (sock, NN_SOL_SOCKET, NN_RCVTIMEO, &to, sizeof(to)) >= 0);

	// SEND
	int sz_n = strlen(argv[1]) + 1; // '\0' too
	printf ("%s: SENDING '%s' ONTO BUS\n", argv[1], argv[1]);
	int send = nn_send (sock, argv[1], sz_n, 0);
	assert (send == sz_n);

	for(;;) {
		nfds = epoll_wait(efd, events, MAX_EVENTS, -1);
		assert(nfds != -1);

		int n, recv;
		for (n = 0; n < nfds; ++n) {
			if (events[n].data.fd == sock_fd) {
				char *buf = NULL;
				recv = nn_recv(sock, &buf, NN_MSG, 0);
				if (recv >= 0) {
					printf ("%s: RECEIVED '%s' FROM BUS\n", argv[1], buf);
					nn_freemsg (buf);
				}
			}
		}
	}
	return nn_shutdown (sock, 0);
}
コード例 #22
0
ファイル: device_demo.c プロジェクト: SEI-AMS/nanomsg
/*  The client runs just once, and then returns. */
int client (const char *url, const char *username)
{
    int fd;
    int rc;
    char *greeting;
    char *msg;

    fd = nn_socket (AF_SP, NN_REQ);
    if (fd < 0) {
        fprintf (stderr, "nn_socket: %s\n", nn_strerror (nn_errno ()));
        return (-1);
    }

    if (nn_connect (fd, url) < 0) {
        fprintf (stderr, "nn_socket: %s\n", nn_strerror (nn_errno ()));
        nn_close (fd);
        return (-1);        
    }

    usleep(1000);

    if (nn_send (fd, username, strlen (username), 0) < 0) {
        fprintf (stderr, "nn_send: %s\n", nn_strerror (nn_errno ()));
        nn_close (fd);
        return (-1);
    }

    /*  Here we ask the library to allocate response buffer for us (NN_MSG). */
    rc = nn_recv (fd, &msg, NN_MSG, 0);
    if (rc < 0) {
        fprintf (stderr, "nn_recv: %s\n", nn_strerror (nn_errno ()));
        nn_close (fd);
        return (-1);
    }

    nn_close (fd);

    /*  Response is not ASCIIZ terminated. */
    greeting = calloc (rc + 1, 1);
    if (greeting == NULL) {
        fprintf (stderr, "calloc: %s\n", strerror (errno));
        return (-1);
    }
    memcpy(greeting, msg, rc);

    nn_freemsg (msg);
    printf ("%s\n", greeting); 
    free (greeting);
    return (0);
}
コード例 #23
0
ファイル: api_main.c プロジェクト: satindergrewal/btcd
void process_json(cJSON *json,char *remoteaddr,int32_t localaccess)
{
    int32_t sock,len,checklen,sendtimeout,recvtimeout; uint32_t apitag; uint64_t tag;
    char endpoint[128],numstr[64],*resultstr,*jsonstr;
    jsonstr = cJSON_Print(json), _stripwhite(jsonstr,' ');
    len = (int32_t)strlen(jsonstr)+1;
    apitag = _crc32(0,jsonstr,len);
    sprintf(endpoint,"ipc://api.%u",apitag);
    free(jsonstr);
    if ( (recvtimeout= juint(json,"timeout")) == 0 )
        recvtimeout = 30000;
    sendtimeout = 30000;
    randombytes((uint8_t *)&tag,sizeof(tag));
    if ( cJSON_GetObjectItem(json,"tag") == 0 )
        sprintf(numstr,"%llu",(long long)tag), cJSON_AddItemToObject(json,"tag",cJSON_CreateString(numstr));
    if ( cJSON_GetObjectItem(json,"apitag") == 0 )
        cJSON_AddItemToObject(json,"apitag",cJSON_CreateString(endpoint));
    if ( remoteaddr != 0 )
        cJSON_AddItemToObject(json,"broadcast",cJSON_CreateString("remoteaccess"));
    if ( localaccess != 0 )
        cJSON_AddItemToObject(json,"localaccess",cJSON_CreateNumber(1));
    jsonstr = cJSON_Print(json), _stripwhite(jsonstr,' ');
    //fprintf(stderr,"localacess.%d remote.(%s) jsonstr.(%s)\r\n",localaccess,remoteaddr!=0?remoteaddr:"",jsonstr);
    len = (int32_t)strlen(jsonstr)+1;
    if ( jsonstr != 0 )
    {
        if ( (sock= nn_socket(AF_SP,NN_PAIR)) >= 0 )
        {
            if ( sendtimeout > 0 && nn_setsockopt(sock,NN_SOL_SOCKET,NN_SNDTIMEO,&sendtimeout,sizeof(sendtimeout)) < 0 )
                fprintf(stderr,"error setting sendtimeout %s\n",nn_errstr());
            if ( nn_connect(sock,SUPERNET_APIENDPOINT) < 0 )
                printf("error connecting to apiendpoint sock.%d type.%d (%s) %s\r\n",sock,NN_PUSH,SUPERNET_APIENDPOINT,nn_errstr());
            else if ( (checklen= nn_send(sock,jsonstr,len,0)) != len )
                printf("checklen.%d != len.%d for nn_send to (%s)\r\n",checklen,len,SUPERNET_APIENDPOINT);
            else
            {
                if ( recvtimeout > 0 && nn_setsockopt(sock,NN_SOL_SOCKET,NN_RCVTIMEO,&recvtimeout,sizeof(recvtimeout)) < 0 )
                    fprintf(stderr,"error setting sendtimeout %s\n",nn_errstr());
                if ( nn_recv(sock,&resultstr,NN_MSG,0) > 0 )
                {
                    printf("Content-Length: %ld\r\n\r\n",strlen(resultstr)+2);
                    printf("%s\r\n",resultstr);
                    nn_freemsg(resultstr);
                } else printf("error getting results %s\r\n",nn_errstr());
            }
            nn_shutdown(sock,0);
        } else printf("error getting pushsock.%s\r\n",nn_errstr());
    }
    free(jsonstr);
}
コード例 #24
0
ファイル: zerocopy.c プロジェクト: prenaux/nanomsg
void test_reallocmsg_reqrep ()
{
    int rc;
    int req;
    int rep;
    void *p;
    void *p2;

    /*  Create sockets. */
    req = nn_socket (AF_SP, NN_REQ);
    rep = nn_socket (AF_SP, NN_REP);
    rc = nn_bind (rep, "inproc://test");
    errno_assert (rc >= 0);
    rc = nn_connect (req, "inproc://test");
    errno_assert (rc >= 0);

    /*  Create message, make sure we handle overflow. */
    p = nn_allocmsg (100, 0);
    nn_assert (p);
    p2 = nn_reallocmsg (p, -1000);
    errno_assert (nn_errno () == ENOMEM);
    nn_assert (p2 == NULL);

    /*  Realloc to fit data size. */
    memcpy (p, "Hello World!", 12);
    p = nn_reallocmsg (p, 12);
    nn_assert (p);
    rc = nn_send (req, &p, NN_MSG, 0);
    errno_assert (rc == 12);

    /*  Receive request and send response. */
    rc = nn_recv (rep, &p, NN_MSG, 0);
    errno_assert (rc == 12);
    rc = nn_send (rep, &p, NN_MSG, 0);
    errno_assert (rc == 12);

    /*  Receive response and free message. */
    rc = nn_recv (req, &p, NN_MSG, 0);
    errno_assert (rc == 12);
    rc = memcmp (p, "Hello World!", 12);
    nn_assert (rc == 0);
    rc = nn_freemsg (p);
    errno_assert (rc == 0);

    /*  Clean up. */
    nn_close (req);
    nn_close (rep);
}
コード例 #25
0
ファイル: pubsub.c プロジェクト: subjam/nanomsg-examples
int client (const char *url, const char *name)
{
    int sock = nn_socket (AF_SP, NN_SUB);
    assert (sock >= 0);
    // TODO learn more about publishing/subscribe keys
    assert (nn_setsockopt (sock, NN_SUB, NN_SUB_SUBSCRIBE, "", 0) >= 0);
    assert (nn_connect (sock, url) >= 0);
    while (1)
    {
        char *buf = NULL;
        int bytes = nn_recv (sock, &buf, NN_MSG, 0);
        assert (bytes >= 0);
        printf ("CLIENT (%s): RECEIVED %s\n", name, buf);
        nn_freemsg (buf);
    }
    return nn_shutdown (sock, 0);
}
コード例 #26
0
ファイル: clinano.c プロジェクト: danburkert/rust-nanomsg
int main ()
{
  int rc;
  int sb;
  int sc;
  int i;
  char buf [4];
  int opt;
  size_t sz;
  char msg[256];
  char* pRecvd = 0;

  // client, running on windows

  sc = nn_socket (AF_SP, NN_PAIR);
  errno_assert (sc >= 0);

  // connect
  rc = nn_connect (sc, SOCKET_ADDRESS);
  errno_assert (rc > 0);

  // send
  memcpy(buf, "WHY\0", 4);
  rc = nn_send (sc, buf, 3, 0);
  printf("client: I sent '%s'\n", buf);
  errno_assert (rc >= 0);
  nn_assert (rc == 3);

  // receive
  rc = nn_recv (sc, &pRecvd, NN_MSG, 0);
  errno_assert (rc >= 0);
  nn_assert (rc == 3);

  sprintf(msg, "client: I received: '%s'\n\0", buf);
  printf(msg);

  // free
  rc = nn_freemsg(pRecvd);
  errno_assert (rc == 0);

  // close
  rc = nn_close (sc);
  errno_assert (rc == 0);

  return 0;
}
コード例 #27
0
ファイル: picture_demo.cpp プロジェクト: AHPlankton/skia
static sk_sp<SkPicture> recv_picture(int socket, PictureHeader* header) {
    static const size_t hSize = sizeof(*header);  // It's easy to slip up and use sizeof(header).

    void* msg;
    int size = nn_recv(socket, &msg, NN_MSG, 0/*flags*/);
    SkDebugf("%d bytes", size);

    // msg is first a fixed-size header, then an .skp.
    memcpy(header, msg, hSize);
    SkMemoryStream stream((uint8_t*)msg + hSize, size - hSize);
    sk_sp<SkPicture> pic = SkPicture::MakeFromStream(&stream);

    SkDebugf(" from proccess %d:", header->pid);

    nn_freemsg(msg);
    return pic;
}
コード例 #28
0
ファイル: reqrep.cpp プロジェクト: krafczyk/nanomsg-examples
int node1 (const char *url)
{
  int sz_date = strlen(DATE) + 1; // '\0' too
  char *buf = NULL;
  int bytes = -1;
  int sock = nn_socket (AF_SP, NN_REQ);
  assert (sock >= 0);
  assert (nn_connect (sock, url) >= 0);
  printf ("NODE1: SENDING DATE REQUEST %s\n", DATE);
  bytes = nn_send (sock, DATE, sz_date, 0);
  assert (bytes == sz_date);
  bytes = nn_recv (sock, &buf, NN_MSG, 0);
  assert (bytes >= 0);
  printf ("NODE1: RECEIVED DATE %s\n", buf);
  nn_freemsg (buf);
  return nn_shutdown (sock, 0);
}
コード例 #29
0
ファイル: ws.c プロジェクト: zakharov/nanomsg
int nn_ws_recv (int s, void *msg, size_t len, uint8_t *msg_type, int flags)
{
    struct nn_iovec iov;
    struct nn_msghdr hdr;
    struct nn_cmsghdr *cmsg;
    void *cmsg_buf;
    int rc;

    iov.iov_base = msg;
    iov.iov_len = len;

    hdr.msg_iov = &iov;
    hdr.msg_iovlen = 1;
    hdr.msg_control = &cmsg_buf;
    hdr.msg_controllen = NN_MSG;

    rc = nn_recvmsg (s, &hdr, flags);
    if (rc < 0)
        return rc;

    /* Find WebSocket opcode ancillary property. */
    cmsg = NN_CMSG_FIRSTHDR (&hdr);
    while (cmsg) {
        if (cmsg->cmsg_level == NN_WS && cmsg->cmsg_type == NN_WS_HDR_OPCODE) {
            *msg_type = *(uint8_t *) NN_CMSG_DATA (cmsg);
            break;
        }
        cmsg = NN_CMSG_NXTHDR (&hdr, cmsg);
    }

    /*  WebSocket transport should always report this header. */
    nn_assert (cmsg);

    /*  WebSocket transport should always reassemble fragmented messages. */
    nn_assert (*msg_type & NN_SWS_FRAME_BITMASK_FIN);

    /*  Return only the message type (opcode). */
    if (*msg_type == (NN_WS_MSG_TYPE_GONE | NN_SWS_FRAME_BITMASK_FIN))
        *msg_type = NN_WS_MSG_TYPE_GONE;
    else
        *msg_type &= NN_SWS_FRAME_BITMASK_OPCODE;

    nn_freemsg (cmsg_buf);

    return rc;
}
コード例 #30
0
ファイル: worker.c プロジェクト: slofurno/nano-mill
int main(void)
{
    printf("what: %d\n", ENOPROTOOPT);
    printf("worker started\n");
    int max_sz = -1;
    int rsnd = 2000000000;
    
    int router = nn_socket(AF_SP, NN_REQ);
    nn_setsockopt(router, NN_SOL_SOCKET, NN_RCVMAXSIZE, &max_sz, sizeof(max_sz));
    int optres = nn_setsockopt(router, NN_REQ, NN_REQ_RESEND_IVL, &rsnd, sizeof(rsnd)); 
    printf("whats this: %d\n", optres);
    assert(optres==0);
    nn_connect(router, WORKERROUTER);

    size_t nbytes;
    char *buf = NULL;

    char *greeting = "hey, another worker is here!";
    nn_send(router, greeting, strlen(greeting), 0); 

    while(1){
    
        nbytes = nn_recv(router, &buf, NN_MSG, 0);
        
        char *uuid = malloc(sizeof(char)*37);
        memcpy((void*)uuid,(const void*)buf,36);
        uuid[36]='\0';
        
        char *tevs = malloc(100);
        sprintf(tevs, "tmp/%s",uuid);
        FILE *file = fopen(tevs, "wb");

        fwrite(buf+36, sizeof(char), nbytes-36, file);
        fclose(file);        
        nn_freemsg(buf);

        printf("got work for id: %s\n",uuid);
        slice *result = forkorsomething(uuid);
        printf("work %s done, reporting\n", uuid);

        nn_send(router, result->bytes, result->len+1, 0);
        free_slice(result);
        printf("report sent\n");
    }    
}