Last active
November 11, 2015 18:14
-
-
Save cdfpaz/70e58312f8f48133babe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifdef _WIN32 | |
#define WIN32_LEAN_AND_MEAN | |
#include <windows.h> | |
#include <winsock2.h> | |
#else | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <netdb.h> | |
#include <unistd.h> | |
#endif | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <time.h> | |
#ifdef _WIN32 | |
#pragma comment(lib,"ws2_32.lib") | |
#endif | |
char *getmessage() { | |
srand(time(0)); | |
const char *header = "POST / HTTP/1.1\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n%s"; | |
const char *json = "\"name\":\"%s\",\"interval\":%d,\"value\":%d"; | |
int l = (strlen(json)*10); | |
char* json_list = (char *)malloc(l); | |
memset(json_list, '\0', l); | |
char tmp[1024] = {0}; | |
strcat(json_list, "{"); | |
sprintf(tmp, json, "system", 60, rand()%11); | |
strcat(json_list, tmp); | |
strcat(json_list, "}"); | |
l = (strlen(json_list) + strlen(header))*2; | |
char* result = (char *)malloc(l); | |
sprintf(result, header, strlen(json_list), json_list); | |
free(json_list); | |
return result; | |
} | |
int senddata() { | |
#ifdef _WIN32 | |
WSADATA wsaData = {0}; | |
SOCKET sock = INVALID_SOCKET; | |
#else | |
int sock = 0; | |
#endif | |
struct sockaddr_in server; | |
char *message = 0; | |
char server_reply[2000] = {0}; | |
int recv_size = 0; | |
#ifdef _WIN32 | |
printf("Initializing socket\n"); | |
if(WSAStartup(0x101,&wsaData) != 0) { | |
printf("ERROR: initializing socket\n"); | |
return -1; | |
} | |
printf("Initialized\n"); | |
#endif | |
if((sock=socket(AF_INET,SOCK_STREAM,0)) < 0 ) { | |
printf("ERROR: creating socket\n"); | |
return -2; | |
} | |
printf("Socket created\n"); | |
server.sin_addr.s_addr = inet_addr("127.0.0.1"); | |
server.sin_family = AF_INET; | |
server.sin_port = htons( 8889 ); | |
if (connect( sock, (struct sockaddr *)&server , sizeof(server)) < 0) { | |
printf("ERROR: connecting socket\n"); | |
return -3; | |
} | |
printf("Socket connected\n"); | |
message = getmessage(); | |
if( send(sock , message , strlen(message) , 0) < 0) | |
{ | |
printf("Send failed\n"); | |
return -4; | |
} | |
free(message); | |
return 0; | |
} | |
int main(int argc, char *argv[]) { | |
time_t last = time(0); | |
for(;;) { | |
if ((time(0)-last)==5) { | |
senddata(); | |
last = time(0); | |
} | |
#ifdef _WIN32 | |
Sleep(100); | |
#else | |
usleep(100 * 1000); | |
#endif | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment