C++网络编程


827 浏览 5 years, 7 months

2.3 因特网服务器2 - SocketSet

版权声明: 转载请注明出处 http://www.codingsoho.com/

实现代码如下

#include "SocketLib/SocketSet.h"
int main()
{    
    int err;                    // for getting errors    
    ListeningSocket lsock;
    lsock.Listen(4000);
    DataSocket dsock;    
    char buffer[128] = "Hello There!";     
    bool done = false;          // used for quitting
    vector<DataSocket>::iterator itr;
    vector<DataSocket> socketlist;     // list of sockets    
    while( !done ){        
        SocketSet sset;                
        // add listen sockets
        sset.AddSocket( lsock );        
        // add all of the data sockets
        for( itr = socketlist.begin(); itr != socketlist.end(); itr++ )
        {
            sset.AddSocket( *itr );
        }        
        int active = sset.Poll( 1000 );
        if(active)
        {
            if(sset.HasActivity(lsock))
            {
                DataSocket dsock;
                dsock = lsock.Accept();
                socketlist.push_back( dsock );
            }         
            // loop through each socket and see if it has any activity
            for( itr = socketlist.begin(); itr != socketlist.end(); itr++ )
            {
                if(sset.HasActivity(*itr))
                {
                    // incomming data
                    cout << "receiving data from socket " << itr->GetSock() << "..." << endl;
                    try
                    {                    
                        err = itr->Receive(buffer, 128);
                        if(err){
                            cout << "Data: " << buffer << endl;
                        }
                    }
                    catch(Exception& e)
                    {                
                        cout << "Exception Error: " << err << endl;
                        socketlist.erase( itr );
                        itr--;
                    }    
                    // if the message was "servquit", then quit the server.
                    if( strcmp( buffer, "servquit" ) == 0 )
                        done = true;
                }
            }
        }    
    }
    return 0;
}

几个地方注意一下:

  • 容器元素从int改成了DataSocket,这个因为Accept的返回数据结构改变了
    vector<DataSocket>::iterator itr;
    vector<DataSocket> socketlist;     // list of sockets
  • select功能封装在sset.Poll( 1000 );
  • Receive返回出错不需要再主函数做过多的处理 (0和-1的场景),这些在DataSocket类里面都已经实现了