2010-07-24 262 views
3

我正在學習boost/asio ad從電子書中編寫了2個程序(客戶端和服務器),只做了很小的修改。 基本上它應該連接到我的服務器。 當我嘗試連接到外部世界(一些隨機http服務器)一切都很好,它的工作原理,但當我改變目的地爲「localhost:40002」它說無效的參數。C++ boost/asio客戶端無法連接到服務器

客戶端代碼:

#include <boost/asio.hpp> 
#include <iostream> 

int main() { 
    try { 
     boost::asio::io_service io_service; 
     boost::asio::ip::tcp::resolver::query query("localhost", 40002); 
     boost::asio::ip::tcp::resolver resolver(io_service); 
     boost::asio::ip::tcp::resolver::iterator destination = resolver.resolve(query); 
     boost::asio::ip::tcp::resolver::iterator end ; 
     boost::asio::ip::tcp::endpoint endpoint; 

     while (destination != end) { 
     endpoint = *destination++; 
     std::cout<<endpoint<<std::endl; 
     } 

     boost::asio::ip::tcp::socket socket(io_service); 
     socket.connect(endpoint); 
    } 
    catch (std::exception& e) 
    { 
     std::cerr << e.what() << std::endl; 
    } 
    return 0; 
} 

我做「netstat的-l」而事實證明,我真的聽我的端口,這樣的服務器,我認爲作品,但從來沒有少,他們不連接

服務器代碼:

#include <boost/asio.hpp> 
#include <iostream> 
#include <string> 
#include <ctime> 
std::string time_string() 
{ 
    using namespace std; 
    time_t now = time(0); 
    return ctime(&now); 
} 
int main() { 

    try { 
     boost::asio::io_service io_service; 
     boost::asio::ip::tcp::acceptor acceptor(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 40002)); 

     for (; ;) { 
     std::cout<<"Listening to"<<std::endl; 
     boost::asio::ip::tcp::socket socket(io_service); 
     acceptor.accept(socket); 

     std::string message = time_string(); 
     boost::system::error_code ignored_error; 
     boost::asio::write(socket, boost::asio::buffer(message), boost::asio::transfer_all(), ignored_error); 
     } 
    } 
    catch (std::exception& e) 
    { 
     std::cerr << e.what() << std::endl; 
    } 
    return 0; 

} 

能有人暗示爲什麼連接不發生

+0

+1用於發佈編譯示例代碼,它使得它更容易回答你的問題。 – 2010-07-24 18:01:44

回答

5

second parameterip::tcp::resolver::query是服務名稱,而不是一個端口號:

boost::asio::ip::tcp::resolver::query query("localhost", 40002); 

應該

boost::asio::ip::tcp::resolver::query query("localhost", "40002"); 

僅供參考,當我在我的系統上編譯代碼失敗:

resolve.cc: In function ‘int main()’: 
resolve.cc:7: error: invalid conversion from ‘int’ to ‘boost::asio::ip::resolver_query_base::flags’ 
resolve.cc:7: error: initializing argument 2 of ‘boost::asio::ip::basic_resolver_query<InternetProtocol>::basic_resolver_query(const std::string&, boost::asio::ip::resolver_query_base::flags) [with InternetProtocol = boost::asio::ip::tcp]’ 

我很驚訝它爲你編譯。

+0

我正在編譯它在Linux上「g ++ -lboost_system -pthread client.cpp」 – kurrata 2010-07-24 18:17:29

+1

我同樣感到驚訝,它在VC 2008 Express上編譯時加上boost 1.38 ... – 2010-07-24 18:20:27

相關問題