#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/select.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define BUFFER_S 1024
void serve(int sd);
main( int argc, char **argv )
{
int PORT;
int lsd; // Listening socket
struct sockaddr_in sin;
int sin_size=sizeof(sin);
int sd; // Socket gia tis nees sindeseis
int enable=1; // &setsockopt
char answr; // y or n
int flag=0;
//Dimiourgia socket
if ( (lsd=socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
fprintf(stderr, "%s: cannot create listening socket: ",argv[0]);
perror(0);
exit(1);
}
PORT=atoi(argv[1]);
printf("* * * Welcome to the SERVER * * *\n");
printf("Socket will bind to port %d\n",PORT);
sin.sin_family = AF_INET; //Internet domain. Kathe socket tautopoieitai apo to IP kai to port.
sin.sin_port = htons(PORT); //Kathorizei to port number. To htons einai 'host to network short', morfi apodekti apo ola ta systimata.
sin.sin_addr.s_addr = htonl(INADDR_ANY);
if ( bind(lsd, &sin, sin_size) < 0 ) { //dinete dieu8insi sto socket
fprintf(stderr, "%s: cannot bind listening socket: ",argv[0]);
perror(0);
exit(1);
}
if ( listen(lsd, 5) < 0 ) { //Me to listen orizoume mikos ouras anamonis.
fprintf(stderr, "%s: cannot listen on socket: ",argv[0]);
perror(0);
exit(1);
}
while ( 1 ) {
printf("\n\nServer ready for connections!\n");
if ( (sd=accept(lsd, &sin, &sin_size)) < 0 ) //dimiourgia neou socket kai enosi me ton client
exit(errno);
do{
flag=0;
answr=' ';
printf("Do you wish to accept the chat invitation ?(y/n)\n");
scanf("%c",&answr);
switch (answr)
{
case 'y':
write(sd,"accept",strlen("accept"));
serve(sd);
break;
case 'Y':
write(sd,"accept",strlen("accept"));
serve(sd);
break;
case 'n':
write(sd,"quit",sizeof("quit"));
break;
case 'N':
write(sd,"quit",sizeof("quit"));
break;
default: printf("answer with y or n %c\n",answr);
getchar();
flag=1;
break;
}
} while (flag==1);
shutdown(sd, 2);
close(sd);
}
}
void serve(int sd)
{
FILE *fs;
int r;
char buffer[BUFFER_S];
memset(buffer,0,sizeof(buffer)); //Katharismos tou buffer.
if ((fs=fopen("server.dat","w"))==NULL)
{
printf("could not open and write to file\n");
exit(1);
}
while(read(sd,&buffer,sizeof(buffer))>0) //diavazei osa byte xorei o buffer
fprintf(fs,"%s",buffer);
printf("\n%s\n",buffer);
fclose(fs);
}