Пример #1
0
/** 
 * @internal Function used to send content from the associated
 * websocket connection
 */
int __myqtt_web_socket_send (MyQttConn            * conn,
			     const unsigned char  * buffer,
			     int                    buffer_len)
{
	noPollConn  * _conn = myqtt_conn_get_data (conn, "__my:ws:conn");
	MyQttCtx    * ctx;
	MyQttMutex  * mutex;
	int           result;

	/* get a reference to the context */
	ctx = conn->ctx;

	/* get mutex */
	mutex = myqtt_conn_get_data (conn, "ws:mutex");
	if (mutex == NULL) {
		myqtt_log (MYQTT_LEVEL_CRITICAL, "unable to find mutex to protect noPoll WebSocket object to read data");
		return -1;
	} /* end if */

	/* acquire lock, operate and release */
	myqtt_mutex_lock (mutex);
	result = nopoll_conn_send_text (_conn, (const char *) buffer, buffer_len);

	/* ensure we have written all bytes but limit operation to 2 seconds */
	result = nopoll_conn_flush_writes (_conn, 2000000, result);

	myqtt_mutex_unlock (mutex);

	return result;
}
Пример #2
0
void listener_on_message(noPollCtx * ctx, noPollConn * conn, noPollMsg * msg, noPollPtr * user_data )
{
           // print the message (for debugging purposes) and reply
        printf ("Listener received (size: %d, ctx refs: %d): (first [removed] bytes, fragment: %d) '%s'\n", 
                nopoll_msg_get_payload_size (msg),
                nopoll_ctx_ref_count (ctx), nopoll_msg_is_fragment (msg), nopoll_msg_get_payload(msg));
    
        // reply to the message
        nopoll_conn_send_text (conn, "Message received", 16);
  
        return;
}
Пример #3
0
nopoll_bool test_sending_and_check_echo (noPollConn * conn, const char * label, const char * msg)
{
  char  buffer[1024];
  int   length = strlen (msg);
  int   bytes_read;

  /* wait for the reply */
  while (nopoll_true) {
    if (nopoll_conn_is_ready (conn))
      break;
    nopoll_sleep (10000);
  } /* end if */

  /* send content text(utf-8) */
  printf ("%s: sending content..\n", label);
  if (nopoll_conn_send_text (conn, msg, length) != length) {
    printf ("ERROR: Expected to find proper send operation..\n");
    return nopoll_false;
  }

  /* wait for the reply (try to read 1024, blocking and with a 3 seconds timeout) */
  bytes_read = nopoll_conn_read (conn, buffer, length, nopoll_true, 3000);
  if (bytes_read > 0)
    buffer[bytes_read] = 0;

  if (bytes_read != length) {
    printf ("ERROR: expected to find 14 bytes but found %d..\n", bytes_read);
    return nopoll_false;
  } /* end if */

  /* check content received */
  if (! nopoll_cmp (buffer, msg)) {
    printf ("ERROR: expected to find message 'This is a test' but something different was received: '%s'..\n",
	    buffer);
    return nopoll_false;
  } /* end if */

  printf ("%s: received reply and echo matches..\n", label);

  /* return that we sent and received the echo reply */
  return nopoll_true;
}
Пример #4
0
//--------------------------------------------------------------------------------------------------
void saveit(void){
//--------------------------------------------------------------------------------------------------
	struct tm t1;
	char tms[430*60][25]; //worst case 1.2MB
	int i,n;
	char *sql;
	//float 8 byte: (7 digits+comma), datetime 24 byte (2015-02-07, 15:22:21.1234) + sample times 3bytes (),;
	int storsize=(sampl*(4*16+26+4) + 200) *sizeof(char);
	char str[430*60*100];
	for (i=0;i<sampl;i++){ //convert timespec to string
		t1 = *gmtime(&dst.ts[piter+i].tv_sec);
		sprintf(tms[i],"%d-%02d-%02d %02d:%02d:%02d.%04ld",t1.tm_year+1900,t1.tm_mon+1, t1.tm_mday, t1.tm_hour,t1.tm_min,t1.tm_sec, dst.ts[piter+i].tv_nsec/100000L);
	}

	if (websocket){ // --------------------------------------------------------------------------------------
		//printf("{\"x\":%ld.%09ld, \"y\":%.9g}\n",dst.ts[piter].tv_sec,dst.ts[piter].tv_nsec,dst.data[piter][0]);
		sprintf(str,"[");
		for(i=0;i<sampl;i++)
			sprintf(str,"%s{\"x\":%ld%03ld, \"a\":%.9g, \"b\":%.9g, \"c\":%.9g, \"d\":%.9g},",str,dst.ts[piter+i].tv_sec,dst.ts[piter+i].tv_nsec/1000000, dst.data[piter+i][0],dst.data[piter+i][1],dst.data[piter+i][2],dst.data[piter+i][3]);
		*(str+strlen(str)-1)=']';
		if (!nopoll_conn_send_text(conn, str, strlen(str)))
			printf("ERROR sending data to websocket server!\n");

	}
	if (savesql){ //-----------------------------------------------------------------------------------------
		if (PQstatus(pg_conn) != CONNECTION_OK){
		    pg_conn = PQconnectdb("dbname = postgres");
			printf("INFO: connected to database postgres\n");
			// Check to see that the backend pg_connection was successfully made 
    		if (PQstatus(pg_conn) != CONNECTION_OK)    {
		        printf("ERROR: pg_connection to database failed: %s",PQerrorMessage(pg_conn));
			    PQfinish(pg_conn);
				exit(-1);
		    }
		}
		sql = (char *) malloc(storsize); 
		sprintf(sql,"INSERT INTO data VALUES ");
		for (i=0;i<sampl;i++){
			n=sprintf(sql,"%s('%s',%.9g,%.9g,%.9g,%.9g),",sql,tms[i], dst.data[piter+i][0],dst.data[piter+i][1],dst.data[piter+i][2], dst.data[piter+i][3]);
		}
		*(sql+n-1)=';';
		//printf("(%i characters of reserved %i)\n",n,storsize);

		pg_res = PQexec(pg_conn, sql);
		if (PQresultStatus(pg_res) != PGRES_COMMAND_OK) {
		    printf("ERROR: SQL command failed: %s", PQerrorMessage(pg_conn));
		    PQclear(pg_res);
			PQfinish(pg_conn);
			exit(-1);
		}
		PQclear(pg_res);

		sprintf(sql,"insert into spsinfo (datetime, sps) select '%s', %g where not exists (select * from spsinfo where datetime = (select max(datetime) from spsinfo) and sps = %g);",tms[0],sps,sps);
		pg_res = PQexec(pg_conn, sql);
		if (PQresultStatus(pg_res) != PGRES_COMMAND_OK) {
		    printf("ERROR: SQL command failed: %s", PQerrorMessage(pg_conn));
		    PQclear(pg_res);
			PQfinish(pg_conn);
			exit(-1);
		}
		PQclear(pg_res);

		free(sql);
		//printf("\tSQL inserted %i records!\n",sampl);

	}

	char dirn[100], fn[40], filen[150];
    FILE *nc=NULL;
	int j;

	if (saveascii || savebin){ //------------------------------------------------------------------------------
		t1 = *gmtime(&dst.ts[piter].tv_sec); //first sample of batch
		test_mkdir(savedirbase);	//home/piter/data
		sprintf(dirn,"%s/%d",savedirbase,t1.tm_year + 1900);
		test_mkdir(dirn);			//home/piter/data/2014
		sprintf(dirn,"%s/%02d", dirn, t1.tm_mon + 1);
		test_mkdir(dirn);			//home/piter/data/2014/12
		sprintf(dirn,"%s/%02d", dirn, t1.tm_mday); 
		test_mkdir(dirn);			//home/piter/data/2014/12/14
		sprintf(fn,"%02d%02d%02d.%04ld",t1.tm_hour,t1.tm_min,t1.tm_sec, dst.ts[piter].tv_nsec/100000L); //file name only
	}	

	if (saveascii){ 	// generate ASCII file: *.cdl (netCDF)
		sprintf(filen,"%s/%s.cdl",dirn,fn);								//path to ASCII file (.cdl)
		nc = fopen(filen, "w");
		if (nc==NULL){
			printf("savefile: Could not open file %s to write!\n",filen);
			//printf("File will be omitted!\n");
			exit(-1);
		}
		fprintf(nc,
			"netcdf %s{\n"
			"dimensions:\n"
			"	a = %i ;\n"
			"	b = %i ;\n"
			"	c = %i ;\n"
			"	d = %i ;\n"
			"variables:\n"
			"	float a(a) ;\n"
			"		a:units = \"mV\" ;\n"
			"	float b(b) ;\n"
			"		b:units = \"mV\" ;\n"
			"	float c(c) ;\n"
			"		c:units = \"mV\" ;\n"
			"	float d(d) ;\n"
			"		d:units = \"mV\" ;\n"
			"     :start=\"%s\";\n"
			"     :sps=%g.f;\n"
			"data:\n", fn,sampl, sampl, sampl, sampl,tms[0],sps);

		const char *s[4];
		s[0] = " a = ";
		s[1] = " b = ";
		s[2] = " c = ";
		s[3] = " d = ";
		for (i=0;i<4;i++){
			fprintf(nc,"%s",s[i]);
			for (j=0;j<sampl;j++)
				fprintf(nc,"%f,",dst.data[piter+j][i]);
			fseek(nc,-1,SEEK_CUR); //del last comma
			fprintf(nc,";\n");
		}
		fprintf(nc,	"}\n");
		if (!fclose(nc))
#ifdef DEBUG
			printf("ASCII file %s written with %i samples each channel.\n",filen, sampl);
#else
			;
#endif
		else
			printf("savefile: Error while writing file %s!\n",filen);
	}
Пример #5
0
int create_client(const char * host, const char * port, int duration)
{
    int rc = 0;

    // Create noPoll context
    noPollCtx * ctx = nopoll_ctx_new ();
    if (!ctx) {
        LogPrintf("Could not create context");
        return 1;
    }
    if (debug_nopoll) {
       nopoll_log_set_handler(ctx, noPollLogger, NULL);
    }

    // Create connection
    uint64_t begin_time = GetTime();
    noPollConn * conn = nopoll_conn_new (ctx, host, port, NULL, NULL, NULL, NULL);
    if (!nopoll_conn_is_ok(conn)) {
        LogPrintf("Failed setting up connection to %s:%s", host, port);
        return 1;
    }

    // Wait till connected
    if (!nopoll_conn_wait_until_connection_ready (conn, 120)) {
        LogPrintf("Could not get connected to %s:%s within 120 seconds. Failed in %d ms",
                host, port, (int)(GetTime() - begin_time));
        return 1;
    }
    LogPrintf("Connected in %d ms.", (int)(GetTime() - begin_time));

    // Don't make any requests. Just sleep for given duration and exit
    // sleep(duration);
    // LogPrintf("Exiting...");
    // return 0;

    // Start the client's request/response loop
    char message[32];
    int messageCount = 0;
    begin_time = GetTime();
    while (true) {
        // Send request
        int requestLen = (rand() % 32000) + 1;
        int requestCount = (rand() % 64) + 1;
        DebugPrintf("Requesting %d messages of %d bytes each [%d]", requestCount, requestLen, messageCount);
        int len = sprintf(message, "Get %d %d", requestLen, requestCount);
        if (nopoll_conn_send_text(conn, message, len) != len) {
            rc = 1;
            LogPrintf("Could not send message: %d", errno);
            break;
        }

        // Collect responses
        for (int index = 0; index < requestCount; index++) {
            if (getResponse(conn, requestLen, index) < 0) {
                rc = 1;
                break;
            }
            messageCount++;
        }
        if (rc == 1)
            break;

        if ((int)(GetTime() - begin_time) > duration * 1000)
            break;
    }

    LogPrintf("Exited after %d ms. Received %d messages.",
            (int)(GetTime() - begin_time), messageCount);

    if (rc == 1) {
        LogPrintf("Error: Client Failed.");
    }
    nopoll_ctx_unref(ctx);
    return rc;
}
Пример #6
0
void*          webSocketery()
{
  noPollCtx			*ctx = nopoll_ctx_new();
  noPollMsg			*msg;
  noPollRole			*role = nopoll_conn_role(NOPOLL_ROLE_UNKNOWN);
  struct noPollHandshake	*fetch;
  noPollConnOpts		*opts;

  /* Comment the log lines to disable loging Debug Warnings and Critical errors (Better not)*/
  //nopoll_log_color_enable(ctx, true);
  //nopoll_log_enable(ctx, nopoll_true);
  /* Initializing the cookie options */
  opts = nopoll_conn_opts_new();

  if (!ctx)
    puts("error ctx is nill");
 
  //To add Cookies use this method below
  /* nopoll_conn_opts_set_cookie(opts, "BAYEUX_BROWSER=56a9-mchhnynonz6ji8a6hs1sh49; JSESSIONID=8gz8e00htqrl15vcm3o9yi95f"); */

  // Websocketery Works for mtgox and others servers but not for m.zpush.ovh it keeps rejecting me for an unknown f*****g 400 error ! Use Methods below to connect to server, a working example is provided
  //nopoll_conn_new(ctx, ip, port, host, get, protocols, origin)    nopoll_conn_new_opts(ctx, opts, ip, port, host, get, protocols, origin)// 
  

  //noPollConn *conn = nopoll_conn_new(ctx , "54.171.156.38" ,"80" ,"m.zpush.ovh:8080" ,"ws://m.zpush.ovh:8080/str/strd" ,NULL, "Authorize");
  noPollConn *conn = nopoll_conn_new(ctx, "54.238.149.121", "80", "websocket.mtgox.com", "/mtgox", NULL, "chat");
  
  if (!nopoll_conn_wait_until_connection_ready(conn, 50) )
    { puts("nopoll_conn failed, timeout"); return (0);}
  if (nopoll_conn_send_text (conn, "hello how are you doing, do we connect ?", 40) != 40)
    {puts("send text just failed...."); return(0);}
  else
    {
      while (! nopoll_conn_is_ready (conn)) {

	if (! nopoll_conn_is_ok (conn)) {
	  printf ("ERROR (4.1 jkd412): expected to find proper connection handshake finished, but found connection is broken: session=%d, errno=%d : %s..\n",
		  (int) nopoll_conn_socket (conn), errno, strerror (errno));
	  return nopoll_false;
	} /* end if */

	/* wait a bit 10ms */
	nopoll_sleep (10000);
      } /* end if */
      nopoll_conn_close (conn);

      /* finish */
      nopoll_ctx_unref (ctx);

      puts("nopoll conn sucess");
      while (nopoll_true)
	{
	  if (nopoll_conn_is_ready(conn))
	    {
	      puts("break");
	      break;
	    }
	  nopoll_sleep(10000);
	}
	  msg = nopoll_conn_get_msg(conn);
	  if (msg)
	    printf("Msg received = %s\n", nopoll_msg_get_payload(msg));
	    
	  if (!nopoll_conn_is_ok(conn))
	    {
	      puts("------------ Connection Dead ----------------");
	      return nopoll_false;
	    }
	
    }
    nopoll_ctx_unref(ctx);
    return (0);
}
Пример #7
0
void listener_on_message (noPollCtx * ctx, noPollConn * conn, noPollMsg * msg, noPollPtr user_data)
{
	const char * content = (const char *) nopoll_msg_get_payload (msg);
	FILE       * file = NULL;
	char         buffer[1024];
	int          bytes;
	int          sent;
	char         example[100];
	int          shown;
	noPollMsg  * aux;
	nopoll_bool  dont_reply = nopoll_false;
	FILE       * open_file_cmd = NULL;
	int          iterator;
	char       * ref;

	/* check for open file commands */
	if (nopoll_ncmp (content, "open-file: ", 11)) {
#if defined(NOPOLL_OS_WIN32)
		open_file_cmd = fopen (content + 11, "ab");
#else
		open_file_cmd = fopen (content + 11, "a");
#endif
		if (open_file_cmd == NULL) {
			printf ("ERROR: unable to open file: %s\n", content + 11);
			return;
		} /* end if */

		/* set handler */
		nopoll_conn_set_on_msg (conn, write_file_handler, open_file_cmd);

		return;
	} /* end if */

	/* printf ("Message received: %s\n", content); */
	if (nopoll_ncmp (content, "close with message", 18)) {
		printf ("Listener: RELEASING connection (closing it) with reason..\n");
		nopoll_conn_close_ext (conn, 1048, "Hey, this is a very reasonable error message", 44);
		return;
	} /* end if */

	if (nopoll_ncmp (content, "release-message", 15)) {
		printf ("Listener: RELEASING previous message..\n");
		nopoll_msg_unref (previous_msg);
		previous_msg = NULL;
		return;
	} /* end if */
	if (nopoll_ncmp (content, "get-cookie", 10)) {
		printf ("Listener: reporting cookie: %s\n", nopoll_conn_get_cookie (conn));
		nopoll_conn_send_text (conn, nopoll_conn_get_cookie (conn), strlen (nopoll_conn_get_cookie (conn)));
		return;
	}

	/* printf ("Checking for set-broken socket: %s\n", content); */
	if (nopoll_ncmp (content, "set-broken-socket", 17)) {
		printf ("Listener: setting broken socket on conn: %p (socket=%d)\n",
			conn, (int) nopoll_conn_socket (conn));
		nopoll_conn_shutdown (conn);
		return;
	} /* end if */

	if (nopoll_ncmp (content, "get-connection-close-count", 26)) {
		printf ("Sending reply to report connection close...\n");
		ref = nopoll_strdup_printf ("%d", connection_close_count);
		nopoll_conn_send_text (conn, ref, strlen (ref));
		nopoll_free (ref);
		return;
	} /* end if */

	if (nopoll_ncmp (content, "1234-1) ", 8)) {
		printf ("Listener: waiting a second to force buffer flooding..\n");
		nopoll_sleep (100000);
		dont_reply = nopoll_true;
	} /* end if */

	/* get initial bytes */
	bytes = nopoll_msg_get_payload_size (msg);
	shown = bytes > 100 ? 99 : bytes;

	memset (example, 0, 100);
	/*	if (! nopoll_msg_is_fragment (msg)) */
		memcpy (example, (const char *) nopoll_msg_get_payload (msg), shown);

	printf ("Listener received (size: %d, ctx refs: %d): (first %d bytes, fragment: %d) '%s'\n", 
		nopoll_msg_get_payload_size (msg),
		nopoll_ctx_ref_count (ctx), shown, nopoll_msg_is_fragment (msg), example);

	if (nopoll_cmp (content, "ping")) {
		/* send a ping */
		nopoll_conn_send_ping (conn);
		return;
	} else if (nopoll_cmp (content, "get-file")) {
		iterator = 0;
		file     = NULL;
		while (nopoll_true) {
#if defined(NOPOLL_OS_WIN32)
			file = fopen ("nopoll-regression-client.c", "rb");
#else
			file = fopen ("nopoll-regression-client.c", "r");
#endif		
			printf ("LISTENER: file pointer (%p, errno=%d : %s)..\n", file, errno, strerror (errno));
			
			if (file)
				break;
			iterator++;
			if (iterator > 3) {
				printf ("ERROR: failed to open nopoll-regression-client.c (fopen call failed)\n");
				nopoll_conn_shutdown (conn);
				return;
			} /* end if */
		} /* end while */

		while (! feof (file)) {
			/* read content */
			bytes = fread (buffer, 1, 1024, file);
			/* send content */
			if (bytes > 0) {
				/* send content and get the result */
				/* printf ("Sending message with %d bytes..\n", bytes); */
				/* nopoll_log_enable (ctx, nopoll_true); */
				
				while (nopoll_true) {
					/* try to send content */
					sent = nopoll_conn_send_text (conn, buffer, bytes);
					/* nopoll_log_enable (ctx, nopoll_false); */
					if (sent != bytes) {
						if (errno == NOPOLL_EWOULDBLOCK) {
							nopoll_sleep (1000);
							/* printf ("   ..retrying..sending message with %d bytes..\n", bytes); */
							continue;
						} /* end if */
						printf ("ERROR: expected to send %d bytes but sent different content size (%d bytes), errno=%d (%d)..\n", 
							bytes, sent, errno, NOPOLL_EWOULDBLOCK);
					} /* end if */
					break;
				}
			} /* end if */
			/* next */
		} /* end while */

		/* now close the handle */
		fclose (file);
		return;
	} /* end if */

	/* check if we have to reply */
	if (dont_reply)
		return;

	if (nopoll_msg_is_fragment (msg)) {
		printf ("Found fragment, FIN = %d (%p)?..\n", nopoll_msg_is_final (msg), msg);
		/* call to join this message */
		aux          = previous_msg;
		previous_msg = nopoll_msg_join (previous_msg, msg);
		nopoll_msg_unref (aux);
		if (! nopoll_msg_is_final (msg)) {
			printf ("Found fragment that is not final..\n");
			printf ("Not replying because frame fragment received..\n");
			return;
		} /* end if */

		printf ("Found final fragment, replying with complete content: %s (refs: %d)..\n",
			(const char *) nopoll_msg_get_payload (previous_msg), 
			nopoll_msg_ref_count (previous_msg));

		/* ok, now found final piece, replying */
		nopoll_conn_send_text (conn, (const char *) nopoll_msg_get_payload (previous_msg), 
				       nopoll_msg_get_payload_size (previous_msg));
		/* release reference */
		nopoll_msg_unref (previous_msg);
		previous_msg = NULL;

		return;
	}

	/* send reply as received */
	printf ("Sending reply... (same message size: %d)\n", nopoll_msg_get_payload_size (msg));
	nopoll_conn_send_text (conn, (const char *) nopoll_msg_get_payload (msg), 
			       nopoll_msg_get_payload_size (msg));
	return;
}