/* * server.c */ #include #include #include #include #include #include "tcplib.h" #define PORT 2527 /* a non-privilege port so all can use */ #define MAX 1024 int main(int argc,char *argv[]) { int s, t; int pid; char buf[MAX]; int n = 0; time_t rawtime; int bytes_sent = 0; s = socketServer(PORT); while (1) { if (s > 0) t = acceptConn(s); else { fprintf(stderr," socket error\n"); exit(1); } fprintf(stderr, "accepted connection\n"); if (t > 0) { pid = fork(); if (pid == 0) { // child process while (1) { sleep(random() % 10 + 1); /* sleeps some random amount of time */ time(&rawtime); sprintf(buf, "%s", ctime(&rawtime)); n = strlen(buf); bytes_sent = write(t, &n, sizeof(int)); bytes_sent = write(t, buf, n); } } close(t); } else { fprintf(stderr," acception error\n"); } } /* while(1) */ close(s); return 0; }