/*

TCP/IP6 IOStreams like class.

Use a template member function with a data stream class as the template
type. pipe_stream, iostream, fstream, tcp_stream6 and others.

Author: Matthew W. Coan
Date: Fri Jun 18 14:04:57 EDT 2010
 
*/

#ifndef _TCP_STREAM_H
#define _TCP_STREAM_H

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>

#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>

#include <netinet/in.h>
#include <arpa/inet.h>

#include <netdb.h>


namespace net_tools {

using namespace std;

static const size_t IO_BUFFER_SIZE = 1024;

class tcp_stream6 {
   bool _error;
   int _fd;
   char _buffer[IO_BUFFER_SIZE];
   const char * _ip_address;
   int _port;
   bool _open;

public:
   tcp_stream6(int fd);

   tcp_stream6(const char * ip_address, 
              const int port);

   virtual ~tcp_stream6();

   void clearerr();

   operator void*();

   tcp_stream6 & operator<<(int i);

   tcp_stream6 & operator<<(const char * str);

   tcp_stream6 & operator<<(const string & str);

   tcp_stream6 & operator>>(string & str);

   tcp_stream6 & operator>>(int & i);

   char get();

   void write(const char * ptr, size_t sz) {
      send(_fd, ptr, sz, 0);
   }

   string read_line(size_t max = 1024) {
      string line;

      char ch = get();

      while(*this) {
         if(ch == '\n')
            break;

         line += ch;

         if(line.size() >= max)
            break;

         ch = get();
      }
  
      return line;
   }

   void close();
};

}

#endif /* _TCP_STREAM_H */
