next up previous contents
Next: About this document ... Up: Sample Code Previous: SynchronisedObject   Contents


GossipConnection

#ifndef _GOSSIPCONNECTION_
#define _GOSSIPCONNECTION_

#include <string>
#include "NetworkException.hxx"
#include <map>
#include <vector>

/** Class to manage and encapsulate all the functions connected with a
 * connection between clients and servers and servers and servers.
 * @author Nathan Dimmock
 */
class GossipConnection
{
private:
  /// Message protcol version number
  const string PROTOCOL_VERSION;
  /// buffer for reading messages off network
  string buffer;
protected:
  /// hostname/IP address of remote end
  string ip_addr;
  /// socket on which communication takes place
  int socket;
  /** Send an XML message to the other end of the connection.
   *  Sends "<msg version = PROTOCOL_VER>"+msg + "</msg>".
   *  @exception NetworkException if it encouters a problem calling write().
   */
  virtual void sendMsg( string msg ) throw( NetworkException &);
  /** Method called by subclasses to parse an XML string and deal with it,
   * handing it back in a parsed form if it can't handle it.
   * @param msg String containing XML message
   * @return multimap of (tagname, data)
   */
  multimap<string, string> parse( const string &msg ) throw(ned21_Exception &);
  /** Method to listen for incoming messages.
   * @return A single unparsed XML message
   */
  string incoming() throw( NetworkException & );
public:
  /** Constructor.  
   * @param hostname IP address/hostname of remote end of connection
   */
  GossipConnection( string hostname );
  /** Constructor for incoming connections. Remote end contacts us on a 
   * well-known port (msock) and then we hand off to another, freshly
   * created, socket.
   * @param msock Master socket on which server accepts incoming connections. 
   * @exception NetworkException Thrown if something network related 
   * goes wrong (e.g. passivesock() encounters an error).
   */
  GossipConnection( int msock ) throw( NetworkException &);
  /// Destructor.  Shuts down the TCP connection.
  virtual ~GossipConnection();
  /// return socket number
  int getSocket() { return socket; }
  /// return IP address of remote end
  const string & getIPAddr() { return ip_addr; }
  /** Request the server list from remote server.
   * (Info returned is handled by calling program to avoid locking server up)
   */
  void getServerList() throw( NetworkException &);
  /** Notify remote end of a change to a user's UserInfo or ContactList
   * @param newinfo The UserInfo message - i.e. <UserInfo>...</UserInfo>
   * or <ContactList>...</ContactList>.
   */
  void infoUpdated( string newinfo ) throw( NetworkException &);
  /** Tell remote end we are about to disconnect from them, with optional 
   *  reason as to why.
   */
  void disconnect(string reason="No reason given") throw( NetworkException &);
};

#endif

#include <cstdio>
#include <unistd.h>
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "MessageParser.hxx"
#include "GossipConnection.hxx"
#include "Utility.hxx"

/// library routine call error number
extern int errno;

GossipConnection::GossipConnection( string hostname ) : PROTOCOL_VERSION("0.1")
{
  ip_addr = hostname;
}

/* FIXME: PROTOCOL_VERSION should be a compile time constant, not 
 * defined manually here!  
 */
GossipConnection::GossipConnection( int msock ) 
       throw( NetworkException &) : PROTOCOL_VERSION("0.1")
{
  struct sockaddr_in fsin;   // from address fo a client
  socklen_t alen = sizeof( fsin );
  // hand off connection to new socket.  
  socket = accept( msock, (struct sockaddr *)&fsin, &alen );
  //set IP address of remote end
  ip_addr = inet_ntoa( fsin.sin_addr );
}

GossipConnection::~GossipConnection()
{
  // shutdown the connection.  
  close(socket);
}

string GossipConnection::incoming() throw( NetworkException &)
{
  // Allocate a receive buffer
  const int BUFSIZE = 2048; // 2k
  char buf[BUFSIZE];
  int cc = 0;
  string returnval;

  // locate the end of the first message (signified by newline)
  unsigned int pos = buffer.find("\n");
  //cout << "Buffer: " << buffer << endl;
  while( pos >= buffer.length() ) // while no more newlines in buffer
  {
      cc = read( getSocket(), buf, BUFSIZE );
      if( cc <= 0 ) // other side has terminated connection
      {
          assert( cerr << "incoming() - other side has closed connection" 
                  << endl );
          throw( NetworkException("Other side has closed connection") );
      }
      buffer += string( buf, cc );
      pos = buffer.find("\n");
  }
  returnval = string( buffer, 0, pos );
  buffer = string( buffer, pos+1, buffer.length() );
  /* Note: buffer is class variable and so persists between calls to 
   * incoming(). It will continue to be filled the next time
   * incoming() is called for this connection.
   */
  return returnval;

multimap<string, string> GossipConnection::parse( const string &msg ) 
      throw( ned21_Exception &)
{
  // parse message
  multimap< string, string > message;
  message.insert(pair<string,string>("ipaddr",getIPAddr() ));
  try { MessageParser p( msg, message ); }
  catch( MessageParser::MsgParseException &e )
  {
    throw( ned21_Exception(string("Parse error: ") + e.what() ) );
  }  
  //cout << "Received: "<< msg << endl;
  return message;
}

void GossipConnection::sendMsg( string msg ) throw( NetworkException &)
{
  string buf("<msg version='");
  buf += PROTOCOL_VERSION;
  buf += "'>"+msg+"</msg>\n";

  // temporarily ignore SIGPIPE signal
  (void)signal (SIGPIPE, SIG_IGN);
  int retcode = write( socket, buf.c_str(), buf.length() );
  (void)signal (SIGPIPE, SIG_DFL);  // unignore SIGPIPE

  if (retcode < 0)
    throw( NetworkException("Could not write to socket: ", errno) );
}

void GossipConnection::getServerList() throw( NetworkException &)
{
  sendMsg( "<reqServerlist></reqServerlist>" );
}

void GossipConnection::disconnect(string reason="No reason given") 
        throw( NetworkException &)
{
  sendMsg( "<disconnect>"+reason+"</disconnect>" );
}

void GossipConnection::infoUpdated( string newinfo ) throw( NetworkException &)
{
  // assume incoming information is already in form <UserInfo>...</UserInfo>
  sendMsg( newinfo );
}



Nathan Dimmock 2001-06-20