• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            阿二的夢(mèng)想船

             

            Poco::TCPServer框架解析

            POCO C++ Libraries提供一套 C++ 的類庫用以開發(fā)基于網(wǎng)絡(luò)的可移植的應(yīng)用程序,功能涉及線程、文件、流,網(wǎng)絡(luò)協(xié)議包括:HTTP、FTP、SMTP 等,還提供 XML 的解析和 SQL 數(shù)據(jù)庫的訪問接口。不僅給我的工作帶來極大的便利,而且設(shè)計(jì)巧妙,代碼易讀,注釋豐富,也是非常好的學(xué)習(xí)材料,我個(gè)人非常喜歡。POCO的創(chuàng)始人在這個(gè)開源項(xiàng)目的基礎(chǔ)上做了一些收費(fèi)產(chǎn)品,也成立了自己的公司,"I am in the lucky position to work for my own company",真是讓人羨慕啊。

            POCO C++ Libraries


            基于POCO的產(chǎn)品


            Poco主頁:http://pocoproject.org/
            Poco文檔:http://pocoproject.org/docs/
            創(chuàng)始人主頁:http://obiltschnig.com/
            公司主頁:http://www.appinf.com/

            我主要用過Net,Data,XML部分,Net里對(duì)socket的封裝類,實(shí)現(xiàn)TCP,HTTP,SMTP協(xié)議的框架,Data里對(duì)MySQL接口封裝,XML里對(duì)DOM標(biāo)準(zhǔn)的實(shí)現(xiàn)。我目前主要是做C++網(wǎng)絡(luò)編程,曾經(jīng)嘗試接觸ACE庫,但覺得太復(fù)雜難理解,而且也沒有條件用于項(xiàng)目,后來發(fā)現(xiàn)了Poco,不僅簡單易用,而且也包含《C++ Networking Programming》中提到的各種模式和框架,更難得的是文檔注釋豐富,看起源碼來相當(dāng)舒服。因此想寫一些筆記,一方面借此加深對(duì)網(wǎng)絡(luò)編程的理解,另一方面也希望和大家多多交流。

            第一篇討論P(yáng)oco::TCPServer框架,先看看Poco::TCPServer有哪些類

            class Net_API TCPServer: public Poco::Runnable
            class Net_API TCPServerConnection: public Poco::Runnable
            class Net_API TCPServerConnectionFactory
            class Net_API TCPServerDispatcher: public Poco::Runnable
            class Net_API TCPServerParams: public Poco::RefCountedObject

            Runnable是一個(gè)抽象類,要求其子類實(shí)現(xiàn)一個(gè)run()函數(shù),run()一般作為線程的入口函數(shù).
            先看看run函數(shù)是如何被調(diào)用的,以TCPServer為例。
             
            void TCPServer::start()
            {
                poco_assert (_stopped);

                _stopped 
            = false;
                _thread.start(
            *this);//這里傳入本類對(duì)象地址
            }

            再看看Thread類的start函數(shù)
             
            class Foundation_API Thread: private ThreadImpl

             

            void Thread::start(Runnable& target)
            {
                startImpl(target);
            }

            這里的ThreadImpl::startImpl是POSIX實(shí)現(xiàn)版本
             
            void ThreadImpl::startImpl(Runnable& target)
            {
                  
                _pData
            ->pRunnableTarget = &target;
                
            if (pthread_create(&_pData->thread, &attributes, runnableEntry, this))
                
            {
                    _pData
            ->pRunnableTarget = 0;
                    
            throw SystemException("cannot start thread");
                }

                  

            pRunnableTarget就指向Runnable了

            void* ThreadImpl::runnableEntry(void* pThread)
            {
                  
                ThreadImpl
            * pThreadImpl = reinterpret_cast<ThreadImpl*>(pThread);
                AutoPtr
            <ThreadData> pData = pThreadImpl->_pData;
                
            try
                
            {
                    pData
            ->pRunnableTarget->run();//在這里
                }

                
            catch (Exception& exc)
                  

            知道run()是如何被調(diào)用了,再看看TcpServer::run()的實(shí)現(xiàn)
             1void TCPServer::run()
             2{
             3    while (!_stopped)
             4    {
             5        Poco::Timespan timeout(250000);
             6        if (_socket.poll(timeout, Socket::SELECT_READ))
             7        {
             8            try
             9            {
            10                StreamSocket ss = _socket.acceptConnection();
            11                // enabe nodelay per default: OSX really needs that
            12                ss.setNoDelay(true);
            13                _pDispatcher->enqueue(ss);
            14            }

            15            catch (Poco::Exception& exc)
            16            

            在第6行調(diào)用標(biāo)準(zhǔn)select函數(shù),準(zhǔn)備好讀后,第10行調(diào)用標(biāo)準(zhǔn)accept建立連接,然后把StreamSocke對(duì)象放入TCPServerDispatcher對(duì)象內(nèi)的隊(duì)列中,可見TCPServer只是建立連接,之后的工作就都交給TCPServerDispatcher了。

            在講TCPServerDispatcher之前,先需要說明的是第10行TCPServer的_socket成員變量類型是ServerSocket,ServerSocket在一個(gè)構(gòu)造函數(shù)中調(diào)用了bind和listen,具體如下
            ServerSocket::ServerSocket(Poco::UInt16 port, int backlog): Socket(new ServerSocketImpl)
            {
                IPAddress wildcardAddr;
                SocketAddress address(wildcardAddr, port);
                impl()
            ->bind(address, true);
                impl()
            ->listen(backlog);
            }
            要注意,盡管ServerSocket類提供了無參構(gòu)造函數(shù),但使用無參構(gòu)造函數(shù)創(chuàng)建的對(duì)象,在TCPServer對(duì)象調(diào)用start()之前,必須先bind和listen。
            "  /// Before start() is called, the ServerSocket passed to
              /// TCPServer must have been bound and put into listening state."

            繼續(xù)看TCPServerDispatcher,沿著TcpServer::run()第13行,我們看它的equeue()
             1void TCPServerDispatcher::enqueue(const StreamSocket& socket)
             2{
             3    FastMutex::ScopedLock lock(_mutex);
             4
             5    if (_queue.size() < _pParams->getMaxQueued())
             6    {
             7        _queue.enqueueNotification(new TCPConnectionNotification(socket));
             8        if (!_queue.hasIdleThreads() && _currentThreads < _pParams->getMaxThreads())
             9        {
            10            try
            11            {
            12                static const std::string threadName("TCPServerConnection");
            13                _threadPool.start(*this, threadName);
            14                ++_currentThreads;
            15            }

            16            catch (Poco::Exception&)
            17            

            第7行enqueueNotification把一個(gè)TCPConnectionNotification入隊(duì),第13行把this交給ThreadPool啟動(dòng)一個(gè)線程,那么這個(gè)線程就要運(yùn)行TCPServerDispatcher的run函數(shù)了,看TCPServerDispatcher::run()

             1void TCPServerDispatcher::run()
             2{
             3    AutoPtr<TCPServerDispatcher> guard(thistrue); // ensure object stays alive
             4
             5    int idleTime = (int) _pParams->getThreadIdleTime().totalMilliseconds();
             6
             7    for (;;)
             8    {
             9        AutoPtr<Notification> pNf = _queue.waitDequeueNotification(idleTime);
            10        if (pNf)
            11        {
            12            TCPConnectionNotification* pCNf = dynamic_cast<TCPConnectionNotification*>(pNf.get());
            13            if (pCNf)
            14            {
            15                std::auto_ptr<TCPServerConnection> pConnection(_pConnectionFactory->createConnection(pCNf->socket()));
            16                poco_check_ptr(pConnection.get());
            17                beginConnection();
            18                pConnection->start();
            19                endConnection();
            20            }

            21        }

                             

            第9行waitDequeueNotification一個(gè)Notification,第12行把這個(gè)通知類型轉(zhuǎn)換成TCPConnectionNotification,聯(lián)系之前的enqueueNotification,大概能才到是什么意思。第15行又出現(xiàn)個(gè)TCPServerConnection。好吧,看來搞清楚TCPServerDispatcher還是要先看下TCPServerConnection,還有TCPConnectionNotification。

            盡管TCPServerConnection繼承了Runable,但沒有實(shí)現(xiàn)run(),它的start()如下
            void TCPServerConnection::start()
            {
                
            try
                
            {
                    run();
                }


            用戶需要繼承TCPServerConnection實(shí)現(xiàn)run函數(shù),看下源碼中的說明,要完成對(duì)這個(gè)socket的處理,因?yàn)閞un函數(shù)返回時(shí),連接就自動(dòng)關(guān)閉了。
            class Net_API TCPServerConnection: public Poco::Runnable
                
            /// The abstract base class for TCP server connections
                
            /// created by TCPServer.
                
            ///
                
            /// Derived classes must override the run() method
                
            /// (inherited from Runnable). Furthermore, a
                
            /// TCPServerConnectionFactory must be provided for the subclass.
                
            ///
                
            /// The run() method must perform the complete handling
                
            /// of the client connection. As soon as the run() method
                
            /// returns, the server connection object is destroyed and
                
            /// the connection is automatically closed.
                
            ///
                
            /// A new TCPServerConnection object will be created for
                
            /// each new client connection that is accepted by
                
            /// TCPServer.

            連接在哪被關(guān)閉的呢,注釋說隨著TCPServerConnection對(duì)象銷毀而關(guān)閉。具體就是,TCPServerConnection類有個(gè)StreamSocket成員,StreamSocket繼承自Socket,Socket類又包含了個(gè)SocketImpl成員,所以就有~TCPServerConnection()->~StreamSocket()->~Socket()->~SocketImpl(),最后~SocketImpl()調(diào)用close()關(guān)閉了連接。

            那么TCPServerConnection對(duì)象何時(shí)被創(chuàng)建何時(shí)被銷毀呢,這下又回到TCPServerDispatcher::run()來了,看TCPServerDispatcher::run()的第15行,創(chuàng)建了TCPServerConnection對(duì)象,第18行調(diào)用TCPServerConnection::start()進(jìn)而調(diào)用TCPServerConnection::run(),第20行塊結(jié)束,TCPServerConnection對(duì)象隨著智能指針銷毀而被銷毀。

            還剩TCPConnectionNotification或者說Notification要搞清楚了,但是要對(duì)Poco的Notifactions模塊源碼進(jìn)行分析的話,本文的篇幅也就太長了,就從文檔來大致看看吧

            Notifications
            Facilities for type-safe sending and delivery of notification objects within a single thread or from one thread to another, also well suited for the implementation of notification mechanisms. A notification queue class for distributing tasks to worker threads, simplifying the implementation of multithreaded servers.

            簡單的說Notifications模塊可用于線程間傳遞消息,簡化多線程服務(wù)器的實(shí)現(xiàn)。具體到TCPServer,就是把已連接的socket,放到NotificationQueue中,并從TheadPool出來一個(gè)線程,線程從NotificationQueue取到這個(gè)socket,從而用TCPServerConnection::run()里的邏輯對(duì)socket進(jìn)行處理。

            至此TCPServer基本分析完畢,還有TCPServerConnectionFactory和TCPServerParams,分別用于產(chǎn)生TCPServerConnection和設(shè)置參數(shù),就不細(xì)說了。

            縱觀Poco::TCPServer,套一下Unix Network Programming》里講的服務(wù)器模型,屬于“在程序啟動(dòng)階段創(chuàng)建一個(gè)線程池之后讓主線程調(diào)用accept,并把每個(gè)客戶連接傳遞給池中某個(gè)可用線程”。Poco1.3.6版里用select作為IO multiplexing。1.3.7版正在嘗試epoll(windows平臺(tái)依然是select),但還未release,跟蹤svn來看也沒有使用edge-triggered模式。套用《The C10K problem》里講的服務(wù)器模型,屬于"Serve many clients with each thread, and use nonblocking I/O and level-triggered readiness notification"??偨Y(jié)起來就是:non-blocking IO + IO multiplexing(level-triggered) + thread pool。

            Poco::TCPServer也許并不能算一個(gè)性能很高的TCP服務(wù)器,但我非常喜歡它的設(shè)計(jì)和編碼風(fēng)格。順便提一下對(duì)底層socket的封裝,由socket類派生的各種子類,ServerSocket在構(gòu)造函數(shù)中進(jìn)行bind和listen,StreamSocket在構(gòu)造函數(shù)進(jìn)行connect,都是非常貼心的設(shè)計(jì)。
             
            下一篇打算分析Poco的Reator框架。

            posted on 2010-09-10 01:05 阿二 閱讀(18874) 評(píng)論(13)  編輯 收藏 引用 所屬分類: Poco

            評(píng)論

            # re: Poco::TCPServer框架解析 2010-09-10 09:23 true

            寫的很好,友情支持,簡單看過POCO,功能上確實(shí)很全,強(qiáng)大,不過沒有自己實(shí)際在項(xiàng)目中使用過,期待更多分析  回復(fù)  更多評(píng)論   

            # re: Poco::TCPServer框架解析 2010-09-10 09:31 true

            ServerSocket在構(gòu)造函數(shù)中進(jìn)行bind和listen,StreamSocket在構(gòu)造函數(shù)進(jìn)行connect,都是非常貼心的設(shè)計(jì)。
            這些在ace里面也有體現(xiàn)。  回復(fù)  更多評(píng)論   

            # re: Poco::TCPServer框架解析 2010-09-10 12:35 一刀

            越來越多的跨平臺(tái)庫,讓人花眼  回復(fù)  更多評(píng)論   

            # re: Poco::TCPServer框架解析 2010-09-10 13:05 阿二

            功能這么強(qiáng)大的可不多哦@一刀
              回復(fù)  更多評(píng)論   

            # re: Poco::TCPServer框架解析 2010-09-10 13:05 阿二

            謝謝鼓勵(lì)@true
              回復(fù)  更多評(píng)論   

            # re: Poco::TCPServer框架解析 2010-09-10 14:06 cpp

            確實(shí)不錯(cuò)!我們需要好庫。
            更希望有一個(gè)所謂的標(biāo)準(zhǔn)的。  回復(fù)  更多評(píng)論   

            # re: Poco::TCPServer框架解析 2010-09-10 14:21 xfun68

            頂!
            Poco現(xiàn)在正慢慢改變我的Cpp開發(fā)之路,\(^o^)/~。
            期待更多介紹Poco的文章~
              回復(fù)  更多評(píng)論   

            # re: Poco::TCPServer框架解析 2010-09-10 14:39 Nine

            一定要支持一下了~~
              回復(fù)  更多評(píng)論   

            # re: Poco::TCPServer框架解析 2010-09-12 11:43 ouyang

            POCO C++的Net好像并沒有用到IOCP,并發(fā)性如何啊?很擔(dān)心性能問題。  回復(fù)  更多評(píng)論   

            # re: Poco::TCPServer框架解析 2010-09-26 09:52 guest

            C++庫需要更多的時(shí)間去考驗(yàn)。。。
            這套庫的話可能用起來方便,但并不就是好,例如
            中間那個(gè)void *...起碼個(gè)人認(rèn)為很不好的,按照語義來說,
            void *到底是指啥?既無類型也也無大小,再次轉(zhuǎn)換的時(shí)候容易出錯(cuò),另外對(duì)其進(jìn)行操作指針+-操作,GNU和ANSI也是不一樣的。  回復(fù)  更多評(píng)論   

            # re: Poco::TCPServer框架解析 2010-09-29 03:45 阿二

            沒明白你的意思。。。 pthread_create要求void* 你能怎么辦呢@guest
              回復(fù)  更多評(píng)論   

            # re: Poco::TCPServer框架解析 2013-05-12 08:56

            請(qǐng)教一個(gè)問題,如果強(qiáng)制中止POCO的線程,是Thread中的哪個(gè)方法?  回復(fù)  更多評(píng)論   

            # re: Poco::TCPServer框架解析 2016-04-21 16:58 ashen

            @清 我剛接觸這個(gè)庫,以前做過1年的linux的c開發(fā),現(xiàn)在做window用這個(gè)庫,看的我好辛苦。  回復(fù)  更多評(píng)論   


            只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。
            網(wǎng)站導(dǎo)航: 博客園   IT新聞   BlogJava   博問   Chat2DB   管理


            導(dǎo)航

            統(tǒng)計(jì)

            常用鏈接

            留言簿

            隨筆分類

            隨筆檔案

            搜索

            最新評(píng)論

            閱讀排行榜

            評(píng)論排行榜

            99热热久久这里只有精品68| 久久国产欧美日韩精品| 日韩人妻无码精品久久久不卡 | 蜜臀久久99精品久久久久久小说| 久久国产视频网| 久久婷婷五月综合色99啪ak| 久久露脸国产精品| 色婷婷狠狠久久综合五月| 日产久久强奸免费的看| 久久伊人亚洲AV无码网站| 久久亚洲国产精品五月天婷| 久久久久噜噜噜亚洲熟女综合| 精品国产青草久久久久福利| 99久久免费只有精品国产| 精品一久久香蕉国产线看播放| 国产精品99久久久久久www| 久久国产三级无码一区二区| 国产精久久一区二区三区| 久久久午夜精品| 久久婷婷五月综合色高清| 91超碰碰碰碰久久久久久综合 | 久久久久久久尹人综合网亚洲| 欧美久久综合性欧美| 久久婷婷人人澡人人| 无遮挡粉嫩小泬久久久久久久| 久久超乳爆乳中文字幕| 国产精品日韩深夜福利久久| 亚洲欧美国产日韩综合久久| 漂亮人妻被黑人久久精品| 国产亚洲成人久久| 色欲综合久久中文字幕网| 久久线看观看精品香蕉国产| 欧洲性大片xxxxx久久久| 久久亚洲中文字幕精品有坂深雪 | 久久精品国产91久久麻豆自制| 久久久久久久综合日本| 久久久亚洲欧洲日产国码二区| 久久国产精品无码网站| 精品久久久久香蕉网| 久久这里都是精品| 久久精品国产91久久综合麻豆自制|