/* Receiver Code (Linux): */

#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>

#define PORT	6001

extern int socket_setup(unsigned short port);
extern int closesocket(int s);
extern int wait_for_request(char *buf, int maxlen);

void
dorecv(int ns, char *s)
{	int fd, n, cnt = 0;
	char buf[4096];

	send(ns, "accept", strlen("accept"), 0);
	printf("receiving %s\n", s);
	while ((n = recv(ns, buf, sizeof(buf), 0)) > 0)
	{	if (strstr(buf, "_EOF_snd_"))
		{	n -= strlen("_EOF_snd_");
			cnt += n;
			break;
		}
		cnt += n;
	}
	if (0)
	{	printf("s_rcv: %s rcv %d bytes\n", s, cnt);
		fflush(stdout);
	}

	sprintf(buf, "%s\tcount\t%d ", s, cnt);
	send(ns, buf, strlen(buf), 0);

	if (0)
	{	printf("done: %s (%d bytes)\n", buf, strlen(buf));
		fflush(stdout);
	}
	closesocket(ns);
}

int
main(int argc, char *argv[])
{	char buf[512];
	int ns;

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

	if (!socket_setup((unsigned short) PORT))
	{	exit(2);	/* err msg already given */
	}

	printf("s_rcv: ready...\n");
	fflush(stdout);
	for (;;)
	{	ns = wait_for_request(buf, sizeof(buf));
		if (ns)
		{	dorecv(ns-1, buf);
	}	}
	exit(1);
}
