所以我决定在我的 C++ 课程之后向前迈出一步,学习如何做一些网络。
在按照如何使用 boost::asio 创建同步客户端的示例之后,一切都很顺利,但是当我试图弄清楚程序的哪个部分实际处理端口时,我感到很困惑。
我知道您输入了一个 IP 地址(例如,我使用 127.0.0.1 作为程序的参数。我通过命令行运行代码:# client 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;
}