/********************************************************************
*       (c) Copyright 2005, Hogeschool voor de Kunsten Utrecht
*                       Hilversum, the Netherlands
*********************************************************************
*
* File name     : daemon.cpp
* System name   : signature
* 
* Version       : $Revision: 1.2 $
*
*
* Description   : Example of a daemon (server) with multiple independent
*		  connections. Each socket connection is served by its own
*		  thread.
*
*
* Author        : Marc_G
* E-mail        : marcg@dinkum.nl
*
*
********************************************************************/

/************
   $Log: daemon.cpp,v $
   Revision 1.2  2005/04/18 10:31:07  marcg
   Modifications for college

   Revision 1.1  2003/04/09 15:53:32  marcg
   Useful demo

*************/

#include <iostream>
#include <socket.h>
#include <unistd.h>	// usleep
#include <fcntl.h>	// threads
#include <pthread.h>	// threads of course


static Socket server;	// The main socket, accepting incoming connections



void *threadfunction(void *arg)
{
Socket *s=(Socket *)arg; // keep compiler and ourselves happy
int bytes_read;
char inbuf[10];

  while(true){
    bytes_read = s->read(inbuf,10);
    if(bytes_read == 0){
      cout << "END\n";
      break;
    }
    cout << "Read: " << inbuf << "\n";
  }
  cout << "Function ends\n";
  delete s; // clean up the local socket
  pthread_exit((void *)0);
}



int main(int argc,char **argv)
{
pthread_t thr;
Socket *new_s;

  server.create();
  server.bind(7777);
  server.listen();

  while(true){
    new_s = new Socket;
    server.accept(*new_s);
    cout << "Connection established\n";

    if(pthread_create(&thr,NULL,threadfunction,(void *)new_s) != 0){
       cout << "Error\n";
    }
  }

  pthread_exit((void *)0);
  return 0;
}

