Example #1
0
int node1 (const char *url, const char *msg)
{
  int sz_msg = strlen (msg) + 1; // '\0' too
  int sock = nn_socket (AF_SP, NN_PUSH);
  assert (sock >= 0);
  assert (nn_connect (sock, url) >= 0);
  printf ("NODE1: SENDING \"%s\"\n", msg);
  int bytes = nn_send (sock, msg, sz_msg, 0);
  assert (bytes == sz_msg);
  return nn_shutdown (sock, 0);
}
Example #2
0
int janus_nanomsg_send_message(janus_transport_session *transport, void *request_id, gboolean admin, json_t *message) {
	if(message == NULL)
		return -1;
	/* Convert to string */
	char *payload = json_dumps(message, json_format);
	json_decref(message);
	/* Enqueue the packet and have poll tell us when it's time to send it */
	g_async_queue_push(admin ? admin_client.messages : client.messages, payload);
	/* Notify the thread there's data to send */
	(void)nn_send(write_nfd[1], "x", 1, 0);
	return 0;
}
Example #3
0
static void ocnotify_newmail(TALLOC_CTX *mem_ctx, struct ocnotify_private ocnotify,
			     uint32_t count, const char **hosts, const char *data)
{
	enum mapistore_error	retval;
	int			sock;
	int			endpoint;
	int			i;
	int			bytes;
	int			timeout;
	int			rc;
	uint8_t			*blob = NULL;
	size_t			msglen;

	if (ocnotify.backend == NULL) {
		oc_log(OC_LOG_ERROR, "No backend specified");
		exit (1);
	}

	retval = mapistore_notification_payload_newmail(mem_ctx, ocnotify.backend, (char *)data, ocnotify.dstfolder,
							ocnotify.sep, &blob, &msglen);
	if (retval != MAPISTORE_SUCCESS) {
		oc_log(OC_LOG_ERROR, "unable to generate newmail payload");
		exit (1);
	}

	sock = nn_socket(AF_SP, NN_PUSH);
	if (sock < 0) {
		oc_log(OC_LOG_FATAL, "unable to create socket");
		exit (1);
	}

	timeout = 200;
	rc = nn_setsockopt(sock, NN_SOL_SOCKET, NN_SNDTIMEO, &timeout, sizeof(timeout));
	if (rc < 0) {
		oc_log(OC_LOG_WARNING, "unable to set timeout on socket send");
	}

	for (i = 0; i < count; i++) {
		endpoint = nn_connect(sock, hosts[i]);
		if (endpoint < 0) {
			oc_log(OC_LOG_ERROR, "unable to connect to %s", hosts[i]);
			ocnotify_flush(ocnotify, hosts[i]);
			continue;
		}
		bytes = nn_send(sock, (char *)blob, msglen, 0);
		if (bytes != msglen) {
			oc_log(OC_LOG_WARNING, "Error sending msg: %d sent but %d expected",
			       bytes, msglen);
		}
		oc_log(OC_LOG_INFO, "message sent to %s", hosts[i]);
		nn_shutdown(sock, endpoint);
	}
}
Example #4
0
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);
}
Example #5
0
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);
}
Example #6
0
/*  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);
}
Example #7
0
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);
}
Example #8
0
JNIEXPORT jint JNICALL Java_org_nanomsg_NanoLibrary_nn_1sendstr(JNIEnv* env,
                                                             jobject obj,
                                                             jint socket,
                                                             jstring str,
                                                             jint flags)
{
    jint ret = 0;
    
    char *cbuf;
    cbuf = (*env)->GetStringUTFChars( env, str , NULL ) ;
    NANO_ASSERT(cbuf);
    ret = nn_send(socket, cbuf, strlen(cbuf) + 1, flags);
    (*env)->ReleaseStringUTFChars(env, str,cbuf);
    return ret;
}
Example #9
0
static int32_t nn_local_broadcast2(int32_t sock,uint64_t instanceid,int32_t flags,uint8_t *retstr,int32_t len)
{
    int32_t i,sendlen,errs = 0;
    if ( sock >= 0 )
    {
        for (i=0; i<10; i++)
            if ( (nn_socket_status2(sock,1) & NN_POLLOUT) != 0 )
                break;
        if ( (sendlen= nn_send(sock,(char *)retstr,len,0)) <= 0 )
            errs++, printf("sending to socket.%d sendlen.%d len.%d (%s) [%s]\n",sock,sendlen,len,nn_strerror(nn_errno()),retstr);
        //else if ( Debuglevel > 2 )
        //    printf("nn_local_broadcast SENT.(%s) len.%d sendlen.%d vs strlen.%ld instanceid.%llu -> sock.%d\n",retstr,len,sendlen,strlen((char *)retstr),(long long)instanceid,sock);
    }
    return(errs);
}
Example #10
0
static PyObject *sockSend(sock_t *self, PyObject *args)
{
    int flags = 0;
    char *buf;
    int buflen;

    if (!PyArg_ParseTuple(args, "t#|i", &buf, &buflen, &flags))
        return NULL;

    if (nn_send(self->sock, buf, buflen, flags) == -1){
        ERR;
        return NULL;
    }
    Py_RETURN_NONE;
}
Example #11
0
int main ()
{
    int rc;
    int pub;
    int sub1;
    int sub2;
    char buf [3];

    pub = nn_socket (AF_SP, NN_PUB);
    errno_assert (pub != -1);
    rc = nn_bind (pub, SOCKET_ADDRESS);
    errno_assert (rc >= 0);
    sub1 = nn_socket (AF_SP, NN_SUB);
    errno_assert (sub1 != -1);
    rc = nn_setsockopt (sub1, NN_SUB, NN_SUBSCRIBE, "", 0);
    errno_assert (rc == 0);
    rc = nn_connect (sub1, SOCKET_ADDRESS);
    errno_assert (rc >= 0);
    sub2 = nn_socket (AF_SP, NN_SUB);
    errno_assert (sub2 != -1);
    rc = nn_setsockopt (sub2, NN_SUB, NN_SUBSCRIBE, "", 0);
    errno_assert (rc == 0);
    rc = nn_connect (sub2, SOCKET_ADDRESS);
    errno_assert (rc >= 0);

    /*  Wait till connections are established to prevent message loss. */
    nn_sleep (10);

    rc = nn_send (pub, "ABC", 3, 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);

    rc = nn_recv (sub1, buf, sizeof (buf), 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);
    rc = nn_recv (sub2, buf, sizeof (buf), 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);

    rc = nn_close (pub);
    errno_assert (rc == 0);
    rc = nn_close (sub1);
    errno_assert (rc == 0);    
    rc = nn_close (sub2);
    errno_assert (rc == 0);

    return 0;
}
Example #12
0
int server (const char *url)
{
    int sock = nn_socket (AF_SP, NN_PUB);
    assert (sock >= 0);
    assert (nn_bind (sock, url) >= 0);
    while (1)
    {
        char *d = date();
        int sz_d = strlen(d) + 1; // '\0' too
        printf ("SERVER: PUBLISHING DATE %s\n", d);
        int bytes = nn_send (sock, d, sz_d, 0);
        assert (bytes == sz_d);
        sleep(1);
    }
    return nn_shutdown (sock, 0);
}
Example #13
0
int testipc_shutdown()
{
    int sb;
    int i;
    int j;
    struct nn_thread threads [THREAD_COUNT];
    printf("test ipc shutdown\n");

    /*  Stress the shutdown algorithm. */

#if defined(SIGPIPE) && defined(SIG_IGN)
	signal (SIGPIPE, SIG_IGN);
#endif

    sb = test_socket (AF_SP, NN_PUB);
    test_bind (sb, SOCKET_ADDRESS);

    for (j = 0; j != TEST_LOOPS; ++j) {
        for (i = 0; i != THREAD_COUNT; ++i)
            nn_thread_init (&threads [i], routine, NULL);
        for (i = 0; i != THREAD_COUNT; ++i)
            nn_thread_term (&threads [i]);
    }

    test_close (sb);

    /*  Test race condition of sending message while socket shutting down  */

    sb = test_socket (AF_SP, NN_PUSH);
    test_bind (sb, SOCKET_ADDRESS);

    for (j = 0; j != TEST_LOOPS; ++j) {
        for (i = 0; i != TEST2_THREAD_COUNT; ++i)
            nn_thread_init (&threads [i], routine2, NULL);
        active = TEST2_THREAD_COUNT;
        while ( active )
        {
            (void) nn_send (sb, "hello", 5, NN_DONTWAIT);
        }
        for (i = 0; i != TEST2_THREAD_COUNT; ++i)
            nn_thread_term(&threads [i]);
    }

    test_close (sb);

    return 0;
}
Example #14
0
JNIEXPORT jint JNICALL Java_org_nanomsg_NanoLibrary_nn_1sendbyte(JNIEnv* env,
                                                             jobject obj,
                                                             jint socket,
                                                             jbyteArray array,
                                                             jint flags)
{
    jbyte* cbuf = 0;
    jint ret = 0;
    
    jsize length = (*env)->GetArrayLength(env, array);
    cbuf = (*env)->GetByteArrayElements(env, array, 0);
    NANO_ASSERT(cbuf);
    ret = nn_send(socket, cbuf, length, flags);
    (*env)->ReleaseByteArrayElements(env, array, cbuf, JNI_ABORT);
    
    return ret;
}
Example #15
0
void janus_nanomsg_destroy(void) {
	if(!g_atomic_int_get(&initialized))
		return;
	g_atomic_int_set(&stopping, 1);

	/* Stop the service thread */
	(void)nn_send(write_nfd[1], "x", 1, 0);

	if(nanomsg_thread != NULL) {
		g_thread_join(nanomsg_thread);
		nanomsg_thread = NULL;
	}

	g_atomic_int_set(&initialized, 0);
	g_atomic_int_set(&stopping, 0);
	JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_NANOMSG_NAME);
}
Example #16
0
JNIEXPORT jint JNICALL Java_org_nanomsg_NanoLibrary_nn_1send(JNIEnv* env,
                                                             jobject obj,
                                                             jint socket,
                                                             jobject buffer,
                                                             jint offset,
                                                             jint length,
                                                             jint flags)
{
    jbyte* cbuf = 0;
    jint ret = 0;

    cbuf = (jbyte*) (*env)->GetDirectBufferAddress(env, buffer);
    NANO_ASSERT(cbuf);
    ret = nn_send(socket, cbuf + offset, length, flags);

    return ret;
}
Example #17
0
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;
}
Example #18
0
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);
}
static void client_task(void *args, zctx_t *ctx, void *pipe)
{
    thr_info *info = (thr_info *) args;
    const char *connect = info->bind_to;
    size_t msg_size = info->msg_size;
    int msg_count = info->msg_count;
    int perf_type = info->perf_type;
    char *buf = (char *) malloc(msg_size);
    memset(buf, 'a', msg_size-1);
    buf[msg_size] = '\0';

    int client_fd = nn_socket(AF_SP, NN_PAIR);
    assert(client_fd != -1);
    int opt = 1;
    int rc = nn_setsockopt(client_fd, NN_TCP, NN_TCP_NODELAY, &opt, sizeof(opt));
    assert(rc == 0);
    rc = nn_connect(client_fd, connect);
    assert(rc >= 0);

    int i;
    INT64 start_ts, end_ts;
    get_timestamp(&start_ts);
    for (i = 0; i < msg_count; i++) {
        int nbytes = nn_send(client_fd, buf, msg_size, 0);
        assert(nbytes == (int)msg_size);
        if (perf_type == LATENCY) {
            nbytes = nn_recv(client_fd, buf, msg_size, 0);
            assert(nbytes == (int)msg_size);
        }
    }

    buf = (char *) malloc(64);
    nn_recv(client_fd, buf, 64, 0);
    assert(strcmp(buf, "well") == 0);
    free(buf);

    get_timestamp(&end_ts);
    if (perf_type == THROUGHPUT) {
        cal_thr(msg_size, msg_count, end_ts - start_ts);
    } else if (perf_type == LATENCY) {
        cal_latency(msg_size, msg_count, end_ts - start_ts);
    }

    zstr_send(pipe, "done");
}
Example #20
0
/* encode a tpl (kv frame) as json. */
void *enc_worker(void *thread_id) {
  char buf[MAX_BUF], *key, *val;
  json_t *o = json_object();
  int rc=-1, len, nc;
  tpl_node *tn;

  while (CF.shutdown == 0) {
    len = nn_recv(CF.ingress_socket_pull, buf, MAX_BUF, 0);
    if (len < 0) {
      fprintf(stderr,"nn_recv: %s\n", nn_strerror(errno));
      goto done;
    }
    /* decode, then re-encode as json */
    json_object_clear(o);
    tn = tpl_map("A(ss)",&key,&val); assert(tn);
    if (tpl_load(tn,TPL_MEM,buf,len) < 0) goto done;
    while(tpl_unpack(tn,1) > 0) {
      json_t *jval = json_string(val);
      json_object_set_new(o, key, jval); 
      free(key); key=NULL;
      free(val); val=NULL;
    }
    tpl_free(tn);

    /* dump the json object, then newline-terminate it. */
    if (CF.verbose>1) json_dumpf(o, stderr, JSON_INDENT(1));
    char *dump = json_dumps(o, JSON_INDENT(0));
    size_t dump_len = strlen(dump);

    /* give the buffer to nano, from here it goes to kaf thread */
    nc = nn_send(CF.egress_socket_push, dump, dump_len, 0);
    free(dump);
    if (nc < 0) {
      fprintf(stderr,"nn_send: %s\n", nn_strerror(errno));
      goto done;
    }
  }

  rc = 0;

 done:
  CF.shutdown = 1;
  json_decref(o);
  return NULL;
}
Example #21
0
void process_json(cJSON *json)
{
    int32_t sock,i,len,checklen,sendtimeout,recvtimeout; uint32_t apitag; uint64_t tag;
    char endpoint[128],*resultstr,*jsonstr;
    jsonstr = cJSON_Print(json), _stripwhite(jsonstr,' ');
    //fprintf(stderr,"jsonstr.(%s)\r\n",jsonstr);
    len = (int32_t)strlen(jsonstr)+1;
    apitag = _crc32(0,jsonstr,len);
    sprintf(endpoint,"ipc://api.%u",apitag);
    free(jsonstr);
    recvtimeout = get_API_int(cJSON_GetObjectItem(json,"timeout"),10000);
    sendtimeout = 5000;
    randombytes(&tag,sizeof(tag));
    cJSON_AddItemToObject(json,"tag",cJSON_CreateNumber(tag));
    cJSON_AddItemToObject(json,"apitag",cJSON_CreateString(endpoint));
    //cJSON_AddItemToObject(json,"timeout",cJSON_CreateNumber(recvtimeout));
    jsonstr = cJSON_Print(json), _stripwhite(jsonstr,' ');
    len = (int32_t)strlen(jsonstr)+1;
    if ( json != 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);
}
Example #22
0
int main ()
{
    int sb;
    int i;
    int j;
    struct nn_thread threads [THREAD_COUNT];

    /*  Stress the shutdown algorithm. */

    sb = test_socket (AF_SP, NN_PUB);
    test_bind (sb, SOCKET_ADDRESS);

    for (j = 0; j != TEST_LOOPS; ++j) {
        for (i = 0; i != THREAD_COUNT; ++i)
            nn_thread_init (&threads [i], routine, NULL);
        for (i = 0; i != THREAD_COUNT; ++i)
            nn_thread_term (&threads [i]);
    }

    test_close (sb);

    /*  Test race condition of sending message while socket shutting down  */

    sb = test_socket (AF_SP, NN_PUSH);
    test_bind (sb, SOCKET_ADDRESS);

    for (j = 0; j != TEST_LOOPS; ++j) {
        for (i = 0; i != TEST2_THREAD_COUNT; ++i)
            nn_thread_init (&threads [i], routine2, NULL);
        nn_atomic_init(&active, TEST2_THREAD_COUNT);

        while (active.n) {
            (void) nn_send (sb, "hello", 5, NN_DONTWAIT);
        }

        for (i = 0; i != TEST2_THREAD_COUNT; ++i)
            nn_thread_term (&threads [i]);
        nn_atomic_term(&active);
    }

    test_close (sb);

    return 0;
}
Example #23
0
ccx_share_status _ccx_share_send(CcxSubEntryMessage *msg)
{
	dbg_print(CCX_DMT_SHARE, "[share] _ccx_share_send\n");
	size_t len = ccx_sub_entry_message__get_packed_size(msg);
	void *buf = malloc(len);
	dbg_print(CCX_DMT_SHARE, "[share] _ccx_share_send: packing\n");
	ccx_sub_entry_message__pack(msg, buf);

	dbg_print(CCX_DMT_SHARE, "[share] _ccx_share_send: sending\n");
	int sent = nn_send(ccx_share_ctx.nn_sock, buf, len, 0);
	if (sent != len) {
		free(buf);
		dbg_print(CCX_DMT_SHARE, "[share] _ccx_share_send: len=%zd sent=%d\n", len, sent);
		return CCX_SHARE_FAIL;
	}
	free(buf);
	dbg_print(CCX_DMT_SHARE, "[share] _ccx_share_send: sent\n");
	return CCX_SHARE_OK;
}
Example #24
0
    void NanoSocket::Send(const NanoMessage& message) throw()
    {
      std::stringstream data;
      data << NanoMessage::SaveMessage(message);

      ios::filtering_streambuf<ios::input> compressor;
      compressor.push(ios::zlib_compressor());
      compressor.push(data);

      std::stringstream compressed;
      ios::copy(compressor, compressed);

      const std::string compressedData = compressed.str();

      std::cout << "Socket " << m_socket << ": "
       << "Sending message type " << message.header.type << ", size " << compressedData.size() << std::endl;
      if (nn_send(m_socket, compressedData.data(), compressedData.size(), 0) < 0)
        throw NanoException{};
    }
Example #25
0
int main (int argc, char *argv [])
{
    const char *bind_to;
    size_t sz;
    int rts;
    char *buf;
    int nbytes;
    int s;
    int rc;
    int i;

    if (argc != 4) {
        printf ("usage: local_lat <bind-to> <msg-size> <roundtrips>\n");
        return 1;
    }
    bind_to = argv [1];
    sz = atoi (argv [2]);
    rts = atoi (argv [3]);

    s = nn_socket (AF_SP, NN_PAIR);
    assert (s != -1);
    rc = nn_bind (s, bind_to);
    assert (rc >= 0);

    buf = malloc (sz);
    assert (buf);
    memset (buf, 111, sz);

    for (i = 0; i != rts; i++) {
        nbytes = nn_recv (s, buf, sz, 0);
        assert (nbytes == sz);
        nbytes = nn_send (s, buf, sz, 0);
        assert (nbytes == sz);
    }

    free (buf);

    rc = nn_close (s);
    assert (rc == 0);

    return 0;
}
Example #26
0
int ss_nn_queue_send(nn_queue_t* nn_queue, uint8_t* message, uint16_t length) {
    int rv = 0;
    
    // XXX: assume message is a C string for now
    RTE_LOG(NOTICE, NM, "nn_queue %s: message id %014lu: %s\n",
        nn_queue->url, nn_queue->tx_messages, message);
    
    rv = nn_send(nn_queue->conn, message, length, NN_DONTWAIT);
    
    if (rv >= 0) {
        // XXX: note: tx_messages is used as seq_num
        // incremented in different code from this
        __sync_add_and_fetch(&nn_queue->tx_bytes, (uint64_t) rv);
    }
    else {
        __sync_add_and_fetch(&nn_queue->tx_discards, 1);
    }
    
    return rv;
}
Example #27
0
/* DELETE command execution. */
void command_delete(comm_thread_t *thread) {
	uint8_t key_size, response = PROTO_OK;
	void *key;
	writer_msg_t *msg;

	// read key length
	read(thread->client_sock, &key_size, sizeof(key_size));
	// read key data
	key = malloc(key_size);
	read(thread->client_sock, key, key_size);
	// create message
	msg = calloc(1, sizeof(writer_msg_t));
	msg->type = WRITE_DEL;
	msg->key.mv_size = (size_t)key_size;
	msg->key.mv_data = key;
	// send the message to the writer thread
	nn_send(thread->writer_sock, &msg, sizeof(msg), 0);
	// send response to the client
	write(thread->client_sock, &response, sizeof(response));
}
Example #28
0
int main ()
{
  int rc;
  int sb;
  int sc;
  int i;
  char buf [4];
  int opt;
  size_t sz;

  // server

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

  // bind
  rc = nn_bind (sb, SOCKET_ADDRESS);
  errno_assert (rc > 0);

  // receive
  bzero(buf, 4);
  rc = nn_recv(sb, buf, sizeof(buf), 0);
  errno_assert(rc >= 0);
  nn_assert(rc == 3);

  printf("server: I received: '%s'\n", buf);

  // send
  memcpy(buf, "LUV\0", 4); // trailing null for later printf
  rc = nn_send (sb, buf, 3, 0);
  printf("server: I sent: '%s'\n", buf);

  errno_assert (rc >= 0);
  nn_assert (rc == 3);
   
  // close
  rc = nn_close (sb);
  errno_assert (rc == 0);

  return 0;
}
void *publisher(void *args)
{
    pthread_detach(pthread_self());
    srand(time(NULL));

    pubsub_info *info = (pubsub_info *) args;
    char *ip = info->broker_ip;
    int port = info->recv_port;
    int msg_size = info->msg_size;
    int num_channels = info->num_channels;
    char **channels = info->channels;

    char pub_addr[SIZE32];
    memset(pub_addr, '\0', SIZE32);
    sprintf(pub_addr, "tcp://%s:%d", ip, port);

    int rc, opt = 1;
    int pub_fd;
    pub_fd = nn_socket(AF_SP, NN_PUSH);
    assert(pub_fd != -1);
    rc = nn_setsockopt(pub_fd, NN_TCP, NN_TCP_NODELAY, &opt, sizeof(opt));
    assert(rc == 0);
    rc = nn_connect(pub_fd, pub_addr);

    char *msg_cont = (char *) malloc(msg_size + 1);
    memset(msg_cont, 'x', msg_size);
    msg_cont[msg_size] = '\0';
    char *msg = (char *) malloc(msg_size + SIZE8);

    while (1) {
        int channel = rand() % num_channels;
        int len = sprintf(msg, "%s %s", channels[channel], msg_cont);
        msg[len] = '\0';
        nn_send(pub_fd, msg, len + 1, 0);
    }

    free(msg_cont);
    free(msg);

    return NULL;
}
Example #30
0
static void nn_global_submit_counter (int i, struct nn_sock *s,
    char *name, uint64_t value)
{
    /* Length of buffer is:
       len(hostname) + len(appname) + len(socket_name) + len(timebuf)
       + len(str(value)) + len(static characters)
       63 + 63 + 63 + 20 + 20 + 60 = 289 */
    char buf[512];
    char timebuf[20];
    time_t numtime;
    struct tm strtime;
    int len;

    if(self.print_statistics) {
        fprintf(stderr, "nanomsg: socket.%s: %s: %llu\n",
            s->socket_name, name, (long long unsigned int)value);
    }

    if (self.statistics_socket >= 0) {
        /*  TODO(tailhook) add HAVE_GMTIME_R ifdef  */
        time(&numtime);
#ifdef NN_HAVE_GMTIME_R
        gmtime_r (&numtime, &strtime);
#else
#error
#endif
        strftime (timebuf, 20, "%Y-%m-%dT%H:%M:%S", &strtime);
        if(*s->socket_name) {
            len = sprintf (buf, "ESTP:%s:%s:socket.%s:%s: %sZ 10 %llu:c",
                self.hostname, self.appname, s->socket_name, name,
                timebuf, (long long unsigned int)value);
        } else {
            len = sprintf (buf, "ESTP:%s:%s:socket.%d:%s: %sZ 10 %llu:c",
                self.hostname, self.appname, i, name,
                timebuf, (long long unsigned int)value);
        }
        nn_assert (len < (int)sizeof(buf));
        (void) nn_send (self.statistics_socket, buf, len, NN_DONTWAIT);
    }
}