我正在學習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;
}
能有人暗示爲什麼連接不發生
+1用於發佈編譯示例代碼,它使得它更容易回答你的問題。 – 2010-07-24 18:01:44