#include <iostream>
#include <socket.h>

#include <fcntl.h>	// threads
#include <pthread.h>	// threads of course



static Socket serv,s;



void *input_thread(void *arg)
{
char inbuf[256];
int bytes_read;

  while(true){
    bytes_read = s.read(inbuf,256);
    for(int i=0;i<bytes_read;i++)cout << inbuf[i];
    cout.flush();
  }
  cout << "INPUT ends\n";
  pthread_exit((void *)0);
}


void *output_thread(void *arg)
{
char c;
int bytes_written;

  while(true){
    cin >> c;
    cin.unsetf(ios::skipws);
    bytes_written=s.write(&c,1);
  }
  cout << "OUTPUT ends\n";
  pthread_exit((void *)0);
}



int main(int argc,char **argv)
{
pthread_t thread_1,thread_2;

  if(string(argv[0])=="server"){
    serv.create();
    serv.bind(7777);
    serv.listen();
    serv.accept(s);
    cout << "Connection established\n";
  } // server
  else{
    s.create();
    s.connect("localhost",7777);
  }

  // Create two threads
  if(pthread_create(&thread_1,NULL,output_thread,NULL) ||
     pthread_create(&thread_2,NULL,input_thread,NULL) )
  {
    cout << "Thread creation fails\n";
    exit(1);
  }

  pthread_exit((void *)0);
}

