
/* Writer.c        

   illustration of nonblocking sockets

   companion to Server.c

   compile, and name executables "server" and  "writer" 

   need two invocations of writer, say on sgi8.cs.ucdavis.edu and 
   sgi9 .cs.ucdavis.edu, while server is running on, say, 
   sausage.engr.ucdavis.edu

   each invocation of writer keeps sending to server, which
   prints it out locally, and also sends the message back, for
   verification that server-to-writer half of the socket is
   working too

   usage:  writer server_hostname who_am_i

   (who_am_i is 0 for one invocation of writer, 1 for the other)    

*/

/* these are needed for socket calls */
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#define BUFSIZE 1000000

#define PORT 2723  /* server port number */

main(argc,argv)
   int argc;  char **argv;

{  int SD,MsgSize,TotRead;
   struct sockaddr_in Addr;
   struct hostent *HostPtr,*gethostbyname();
   char Buf[BUFSIZE],
        OutBuf[BUFSIZE];
   int WhoAmI,NB;
   int I; char C;

   /* open a socket */
   SD = socket(AF_INET,SOCK_STREAM,0);

   /* set up for an Internet connection to the host whose 
      name was specified by the user on the command line */
   Addr.sin_family = AF_INET;
   WhoAmI = atoi(argv[2]);
   Addr.sin_port = PORT;
   /* get IP address of host */
   HostPtr = gethostbyname(argv[1]);
   memcpy(&Addr.sin_addr.s_addr,
      HostPtr->h_addr_list[0],HostPtr->h_length);

   /* OK, now connect */
   connect(SD,&Addr,sizeof(Addr));

   for(I = 0; ; I++)  {
      
      /* form the message and send it */
      sprintf(Buf,"*** %d %d   ",WhoAmI,I);
      write(SD,Buf,strlen(Buf));

      /* check that server can send to us too */
      NB = read(SD,OutBuf,sizeof(OutBuf));
      printf("got back %d bytes:  ",NB);
      printf("\n");
      write(1,OutBuf,NB);

      /* to allow for user to experiment with different interleavings
         of messages from the two invocations of Writer.c, wait til
         user hits a key */
      scanf("%c",&C);
   }
}

/* if messages were longer, the call to read() would have to be in
   a loop, to make sure all bytes are received

   this is normally not a problem for calls to write(), but in the
   case of nonblocking sockets it is safest to put a write() in a 
   loop too */



