Poco庫網絡模塊例子解析1-------字典查詢

Poco的網絡模塊在Poco::Net名字空間下定義   下面是字典例子解析
ios



#include "Poco/Net/StreamSocket.h"   //流式套接字
#include "Poco/Net/SocketStream.h"   //套接字流
#include "Poco/Net/SocketAddress.h"   //套接字地址
#include "Poco/StreamCopier.h"  //流複製器
#include "Poco/Path.h"   //路徑解析器
#include "Poco/Exception.h"  //異常
#include <iostream>


using Poco::Net::StreamSocket;
using Poco::Net::SocketStream;
using Poco::Net::SocketAddress;
using Poco::StreamCopier;
using Poco::Path;
using Poco::Exception;

//從dict.org查找詞語
int main(int argc, char** argv)
{
    const std::string HOST("dict.org");    //字典查詢服務器
    const unsigned short PORT = 2628; //端口
    
    if (argc != 2)
    {
        Path p(argv[0]); //解析路徑
        std::cout << "usage: " << p.getBaseName() << " <term>" << std::endl;  //獲取BaseUrl
        std::cout << "       looks up <term> in dict.org and prints the results" << std::endl;
        return 1;
    }
    std::string term(argv[1]); //要查詢的單詞 做爲 運行參數1
    
    try
    {
        SocketAddress sa(HOST, PORT); //定義一個套接字 地址對象  相似winsock的 sockaddr_in
        StreamSocket sock(sa);  //建立 流式套接字
        SocketStream str(sock); //建立套接字流用於進行 輸入輸出 相似於winsock recv send
        
        str << "DEFINE ! " << term << "\r\n" << std::flush;  //發送查詢命令
        str << "QUIT\r\n" << std::flush;  //查詢命令結束

        sock.shutdownSend(); //關閉發送方的連接
/// Writes all bytes readable from istr to ostr, using an internal buffer.
        /// Returns the number of bytes copied. StreamCopier::copyStream(str, std::cout); //拷貝全部輸入流到 輸出流上 也就是說把 查詢返回的結果 輸出到std::cout }
catch (Exception& exc) { std::cerr << exc.displayText() << std::endl; //異常處理 return 1; } return 0; }
相關文章
相關標籤/搜索