gpt4 book ai didi

C++ - 在同一程序中运行一个服务器线程和一个客户端线程

转载 作者:行者123 更新时间:2023-11-28 06:52:11 24 4
gpt4 key购买 nike

我一直在尝试修改 boost 的白天服务器/客户端示例,使其在 2 个线程中运行,但没有成功:

#include <ctime>
#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/thread.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);
}

void ServerThread()
{
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13));

for (;;)
{
std::cout << "why?";
tcp::socket socket(io_service);
acceptor.accept(socket);
std::string message = make_daytime_string();
boost::system::error_code ignored_error;
boost::asio::write(socket, boost::asio::buffer(message),
boost::asio::transfer_all(), ignored_error);
}

}

void ClientThread()
{
try
{
boost::asio::io_service io_service;

std::string hostString;

std::cout << "Please enter the host: ";
std::cin >> hostString;

tcp::resolver resolver(io_service);
tcp::resolver::query query(hostString, "daytime");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

tcp::socket socket(io_service);
boost::asio::connect(socket, endpoint_iterator);
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}

int main()
{
boost::thread s(&ServerThread);
boost::thread c(&ClientThread);

c.join();
s.join();

return 0;
}

两个线程立即依次运行,不会正确处理。我想我需要沿着 fork 做点什么?请帮忙告诉我代码有什么问题,谢谢。

最佳答案

在您的客户端中,您省略了接收数据的代码部分。连接后放入:

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);
std::cout.write(buf.data(), len);
}

您还需要包含 boost/array.hpp。

关于C++ - 在同一程序中运行一个服务器线程和一个客户端线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23735340/

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