/* ======================================================> asynch_server.c * * Standard brain-dead server. Receive and send back junk. * * ===================================================================== */ #include #include #include #include #include int main(int argc, char *argv[]) { int sock, clientsock, mlen, addrsize, msgct, chc, chct; int rnd; struct sockaddr_in addr; char ch, buf[256]; if (argc < 2) { fprintf (stderr, "Syntax: servername port\n"); exit (0); } printf ("Server is starting - don't forget to get rid of me when done\n"); /* * Create a socket to use. */ sock = socket(AF_INET, SOCK_STREAM,0); if (sock == -1) { perror("opening socket"); exit(-1); } /* * Bind a name to the socket. Since the server will bind with * any client, the machine address is zero or INADDR_ANY. The * bind call sets up the socket-port pair, where the socket specifies * the protocol and the port is used by the operating system to direct * messages to this program. */ addr.sin_family = AF_INET; addr.sin_port = htons (atoi (argv[1])); addr.sin_addr.s_addr = htonl (INADDR_ANY); if (bind(sock, &addr, sizeof (struct sockaddr_in)) == -1) { perror ("on bind"); exit (-1); } /* * Make the socket available. The listen call causes the operating * system to make the socket available for connections. */ if (listen(sock,1) == -1) { perror("on listen"); exit(-1); } /* * Wait for a client to connect. */ addrsize = sizeof(struct sockaddr_in); clientsock = accept(sock, &addr, &addrsize); if (clientsock == -1) { perror("on accept"); exit(-1); } /* printf("connection made with client %s", inet_ntoa (addr . sin_addr)); */ /* * Receive and print a client message where a null character terminates. * Note that a single receive may not work in some cases, but is OK for * a simple example. */ do { mlen = recv (clientsock, buf, 256, 0); /* printf ("Server has recieved data\n"); */ if (mlen == 0) continue; if (strncmp (buf, "quit", 4) == 0) break; /* printf ("Server sending message\n"); */ rnd = (int) (1.0 + 3.0 * ((float)random ())/(float)RAND_MAX); switch (rnd) { case 1: send (clientsock, "Got your message", 17, 0); break; case 2: send (clientsock, "Whaaazzzzuuuupppp", 18, 0); break; case 3: send (clientsock, "I know what you did last time slice", 36, 0); break; case 4: send (clientsock, "Howdy, pardner", 15, 0); break; } } while (1); /* * Close the client socket and also the server socket */ close(clientsock); close(sock); }