// $Header: /usr/u/moudgill/project/Socket/RCS/server1.C,v 1.7 1992/10/02 18:34:02 moudgill Exp moudgill $
// 17th December, 1991. Mayan Moudgill.

static const char rcsid[] = "$Id";

#include "sstream.h"
#include <sys/socket.h>
#ifdef __linux__
#include <stdlib.h>
#include <unistd.h>
#else
#include <osfcn.h>
#endif

void pipedef(sstream& s)
{
   cerr << "lost other end of " << s.sd() << "\n";
   exit(1);
}

int  n;
void getcount(sstream&, int x)
{
   cerr << "getcount " << x << "\n";
   n = x;
}

void  negnum(sstream &t, int)
{
int c;

   t >> c;
   if( !t ) {
      cerr << "couldn't recv\n" ;
      exit(2);
   }
   cerr << "read " << c << "\n";
   t << (-c) << "\n" ;
   if( !t ) {
      cerr << "couldn't send\n";
      exit(3);
   }
} 

void main(int argc, char * argv[])
{
// sstream::showtrace = 1;
// sstream::showerror = 1;
// sstream::showmonitor = 1;
// sstream::showsyscall = 1;

sstream s;
sstream t;

   if( argc < 2) {
      cerr << "error: usage : " << argv[0] << " <port>\n";
      exit(4);
   }

   s.setbuf(0,0);
   s.open(atoi(argv[1]));

   if( !s  ) {
      cerr << "could not open\n";
      exit(5);
   }

   cerr << "server " << s.sd() << " bound to " << s.host() << " "
	 << s.port() << "\n";

   t.setbuf(0,0);
   t.accept(s);
   if( !t ) {
      cerr << "could not accept\n";
      exit(6);
   }
   cerr << "server " << t.sd() << " connected to " << t.tohost() << " "
	 << t.toport() << "\n";

   t.pipehandler(pipedef);
   t.urghandler(getcount);
   t.iohandler(negnum);

   pause();
   cerr << "going to process " <<  n << " numbers\n";

   for(int i = 0; i < n; i++) {
      cerr << "processed " << i << "\n";
      pause();
   }
}
