Main Page | Namespace List | Class Hierarchy | Class List | File List | Namespace Members | Class Members | File Members | Related Pages

NetworkListener.hpp

Go to the documentation of this file.
00001 /*==========================================================================
00002  * Copyright (c) 2004 University of Massachusetts.  All Rights Reserved.
00003  *
00004  * Use of the Lemur Toolkit for Language Modeling and Information Retrieval
00005  * is subject to the terms of the software license set forth in the LICENSE
00006  * file included with this software, and also available at
00007  * http://www.lemurproject.org/license.html
00008  *
00009  *==========================================================================
00010  */
00011 
00012 
00013 //
00014 // NetworkListener
00015 //
00016 // 23 March 2004 -- tds
00017 //
00018 
00019 #ifndef INDRI_NETWORKLISTENER_HPP
00020 #define INDRI_NETWORKLISTENER_HPP
00021 
00022 #include "lemur-compat.hpp"
00023 #include "indri/NetworkStream.hpp"
00024 namespace indri
00025 {
00027   namespace net
00028   {
00029     
00030     class NetworkListener {
00031       socket_t _socket;
00032 
00033     public:
00034       NetworkListener() : _socket(-1) {}
00035       ~NetworkListener() {
00036         close();
00037       }
00038 
00039       bool listen( unsigned int port ) {
00040         int result;
00041  
00042         lemur_compat::initializeNetwork();
00043         _socket = ::socket( AF_INET, SOCK_STREAM, 0 );
00044 
00045         sockaddr_in sa;
00046         sa.sin_addr.s_addr = INADDR_ANY;
00047         sa.sin_port = htons(port);
00048         sa.sin_family = AF_INET;
00049         memset( &sa.sin_zero, 0, sizeof sa.sin_zero );
00050 
00051         result = ::bind( _socket, (const sockaddr*) &sa, sizeof sa );
00052         if( result ) {
00053           close();
00054           LEMUR_THROW( LEMUR_IO_ERROR, "Wasn't able to bind port " + i64_to_string(port) );
00055         }
00056   
00057         result = ::listen( _socket, 8 );
00058 
00059         if( result ) {
00060           close();
00061           LEMUR_THROW( LEMUR_IO_ERROR, "Wasn't able to listen on port " + i64_to_string(port) );
00062         }
00063 
00064         return true;
00065       }
00066 
00067       NetworkStream* accept() {
00068         assert( _socket != -1 );
00069         socket_t s = ::accept( _socket, 0, 0 );
00070         return new NetworkStream(s);
00071       }
00072 
00073       void close() {
00074         lemur_compat::closesocket(_socket);
00075         _socket = -1;
00076       }
00077     };
00078   }
00079 }
00080 
00081 #endif // INDRI_NETWORKLISTENER_HPP

Generated on Tue Jun 15 11:02:54 2010 for Lemur by doxygen 1.3.4