所以我決定在C++課程之後向前邁進一步,學習如何做一些網絡。boost :: asio如何確定要連接的端口?
在學習如何使用boost :: asio創建一個同步客戶端的例子之後,一切進展順利,但是當試圖找出程序實際處理端口的哪一部分時,我很難過。 。# client 127.0.0.1
而且,代碼的服務器端,運行於:
我明白你輸入一個IP地址(例如我用127.0.0.1作爲程序的參數我通過命令行運行的代碼端口13,如下所示:http://www.boost.org/doc/libs/1_52_0/doc/html/boost_asio/tutorial/tutdaytime2.html
下面是從網站的完整代碼: (也可以在這裏找到:http://www.boost.org/doc/libs/1_52_0/doc/html/boost_asio/tutorial/tutdaytime1.html
//
// client.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2012 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: client <host>" << std::endl;
return 1;
}
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(argv[1], "daytime");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::socket socket(io_service);
boost::asio::connect(socket, endpoint_iterator);
for (;;)
{
boost::array<char, 128> buf;
boost::system::error_code error;
size_t len = socket.read_some(boost::asio::buffer(buf), error);
if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
std::cout.write(buf.data(), len);
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
感謝您的快速響應。我有一個問題,我只是嘗試輸入我的選擇端口,例如「133」而不是「白天」。這是使用此功能的正確方法嗎? – TheAJ
@TheAJ是的,無論是名稱(來自'/ etc/services')還是一個數字(作爲一個字符串)都可以工作。請參閱[參考](http://www.boost.org/doc/libs/1_52_0/doc/html/boost_asio/reference/ip__basic_resolver_query/basic_resolver_query/overload3.html)。 –