gpt4 book ai didi

c++ - 简单的服务器/客户端 boost 示例不起作用

转载 作者:可可西里 更新时间:2023-11-01 02:36:50 25 4
gpt4 key购买 nike

学习 boost ,编译自己的白天服务器客户端example .因为我不能使用示例中的端口 13,所以我只更改了服务器和客户端示例中的端口号。服务器运行良好,但客户端似乎没有连接,也没有报错。

客户端的输入数据是“127.0.0.1”。

服务器:

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

using boost::asio::ip::tcp;

std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}

int main()
{
try
{
boost::asio::io_service io_service;

tcp::endpoint endpoint(tcp::v4(), 8087);
tcp::acceptor acceptor(io_service, endpoint);

for (;;)
{
tcp::iostream stream;
acceptor.accept(*stream.rdbuf());
stream << "test" << make_daytime_string();
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}

return 0;
}

和客户:

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

using boost::asio::ip::tcp;

int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: daytime_client <host>" << std::endl;
return 1;
}

tcp::iostream s(argv[1], 8087);
std::string line;
std::getline(s, line);
std::cout << line << std::endl;
}
catch (std::exception& e)
{
std::cout << "Exception: " << e.what() << std::endl;
}

return 0;
}

最佳答案

对我有用的是改变我创建端点的方式

tcp::endpoint( tcp::v4(), port );

tcp::endpoint( boost::asio::ip::address::from_string("127.0.0.1"), port );

第一种方法创建一个端点 0.0.0.0,它在 Mac OS X 上运行良好,但在 Windows(XP,使用 MSVC 2008 构建)上给出“无效”消息。

我不介意知道为什么会有所不同,但至少它有效。

关于c++ - 简单的服务器/客户端 boost 示例不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/717618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com