/* Sender Code (Windows): */

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <winsock2.h>

#include <time.h>

#define PORT	(unsigned short) 6001
#define NIKS	"128.149.8.110"
#define SELF	"127.0.0.1"
#define PORT_USED	NIKS

extern int poll_cpu(char *, unsigned short, char *, int, int);
extern inisockets(void);

#define N	1000000	/* number of iterations */
#define M	10000	/* length of state descriptor */

int
main(int argc, char *argv[])
{	int i = 0, n, s, rcnt, scnt=0;
	char src[M], inm[64], pn[64];
	time_t start, end;

	if (argc != 1)
	{	printf("usage: w_snd\n");
		exit(1);
	}

	if (!inisockets())
	{	printf("w_snd: no socket\n");
		exit(2);
	}

	memset(src, 0, M);
	while (i < M)
	{	strcpy(&src[i], "Now is the time for all good people. ");
		i += strlen("Now is the time for all good people. ");
	}

	strcpy(inm, "performance_test");

	s = poll_cpu(PORT_USED, PORT, inm, strlen(inm), 1);
	if (s <= 0)
	{	printf("w_snd: bad poll\n");
		exit(1);
	}
	printf("starting\n");
	start = time(0);
	for (i = scnt = 0; i < N; i++)
	{	scnt += M;
		if (send(s, src, M, 0) != M)
		{	printf("w_snd: connection broken\n");
			exit(1);
	}	}
	end = time(0);
	printf("time: %.2lf sec (scnt %d)\n", difftime(end, start), scnt);

	if (send(s, "_EOF_snd_", strlen("_EOF_snd_"), 0) != strlen("_EOF_snd_"))
	{	printf("error on final send\n");
	}

	for (i = 0; ; i++)
	{	memset(src, 0, 512);
		n = recv(s, src, 32, 0);

		if (n > 0)
		{	src[n] = '\0';
			sscanf(src, "%s\tcount\t%d ", pn, &rcnt);
	
			if (strcmp(pn, inm) != 0)
			{	printf("\tmismatch (n=%d)--'%s' (%d) '%s' (%d)\n",
					n, pn, strlen(pn),
					inm, strlen(inm));
			}
			if (rcnt != scnt)
			{	printf("\tcount mismatch %d != %d\n", rcnt, scnt);
			}
			break;
		}
		perror("try again");
		send(s, "_EOF_snd_", strlen("_EOF_snd_"), 0);
		_sleep(1);
	}

	closesocket(s);

	exit(0);
}
