#include <unistd.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>

extern "C" void wait_for_continue();

void read_msg(int file);
int main()
{
	//wait_for_continue();

	int s,msgsock,rval;
	struct sockaddr_in in_addr;
	int Sport =2222
;
	char buff[128];
	int True =1;
	//wait_for_continue();
	printf("Create new socket..\n");
	s = socket(AF_INET, SOCK_STREAM, 0);
	printf("socket = %d\n",s);
	if (s == -1) {
		printf("ERROR: Could not create socket!\n");
		return -1;
	}


	in_addr.sin_port = htons(Sport);
	in_addr.sin_family = AF_INET;
	in_addr.sin_addr.s_addr = INADDR_ANY;
	if (  bind(s, (struct sockaddr *)&in_addr, sizeof (in_addr)) == -1) {
		printf("ERROR: Could not bind!\n");
		close(s);
		return -1;
	}
	printf("Bind socket to %d\n", Sport);
	if ( listen(s, 5) == -1) {
		printf("ERROR: Could not listen!\n");
		close(s);
		return -1;
	}
	printf("wait...\n");
	int k = 0 ; 
	while (1 && k++<10)
	{
		msgsock =accept(s,0,0);
		printf("accepted, msgsock %d \n",msgsock);
		if (msgsock==-1)
			printf("ERROR: accept!\n");
		else
			{
				//read_msg(msgsock);
				memset(buff,0,sizeof(buff));
				printf("writing \n");
				char * txt = " from srever 2222: hi there\n";
				int r =write(msgsock,txt,strlen(txt));
				if (r <0)
					printf("ERROR: write!\n");
				int re =read(msgsock,buff,10);
				printf(" from client %s\n",buff);
				read_msg(msgsock);
			}
		//close (msgsock);
		
	}
}


void read_msg(int file)
{
	char line[128];
	printf(" file stfin stdout %d %d %d \n",file,fileno(stdin),fileno(stdout));

	FILE *f ;
	f = fdopen(file,"r+");
	if(f==NULL)
	{
		printf("error in file\n");
		perror("dopen");
		//close(file);
	}
	//fprintf(f,"hi there\n");
	//fflush(f);

	//char * txt = "from srever 2222: hi there\n";
	//fwrite(txt,strlen(txt),1,f);
	//fflush(f);
	int c ;
	while((c= fgetc(f))){
		printf("%c",c); 
		if (c=='\n') {
			char * t = "get the text \n";
			int r =write(file,t,strlen(t));
			if (r <0)
				printf("ERROR: write!\n");
		}
	}

	//int r =fread(line,1,10,f);
	//printf(" line %s\n",line);

	//fclose(f);
}

