gpt4 book ai didi

Boost asio发送和接收消息

转载 作者:行者123 更新时间:2023-12-04 22:45:39 25 4
gpt4 key购买 nike

我正在尝试使用TCP从客户端和服务器发送和接收消息。我正在尝试使用线程,但我根本不知道该怎么做。我可以很好地连接到服务器,但是我需要能够按需从两个地方发送和接收消息。我一直在搜索几个小时,却空无一人,因为Google上的所有结果都过于复杂和困惑。

struct Client
{
boost::asio::ip::tcp::socket socket;

Client(const char* host = HOST, const char* port = PORT) : socket(io_service)
{
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::resolver::iterator endpoint = resolver.resolve(boost::asio::ip::tcp::resolver::query(HOST, PORT));
boost::asio::connect(this->socket, endpoint);
};
};

到目前为止,我已经为客户准备了所有这些。

对于服务器:
const int PORT = 52275;

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(), PORT));

{
boost::asio::ip::tcp::socket socket(io_service);
acceptor.accept(socket);
main();
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
}
}

最佳答案

由于假定您只想以最简单的方式发送/any/消息显然是安全的:

Live On Coliru

#include <boost/asio.hpp>

struct Client
{
boost::asio::io_service& io_service;
boost::asio::ip::tcp::socket socket;

Client(boost::asio::io_service& svc, std::string const& host, std::string const& port)
: io_service(svc), socket(io_service)
{
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::resolver::iterator endpoint = resolver.resolve(boost::asio::ip::tcp::resolver::query(host, port));
boost::asio::connect(this->socket, endpoint);
};

void send(std::string const& message) {
socket.send(boost::asio::buffer(message));
}
};


#include <iostream>

static const int PORT = 52275;

void client_thread() {
boost::asio::io_service svc;
Client client(svc, "127.0.0.1", std::to_string(PORT));

client.send("hello world\n");
client.send("bye world\n");
}

void server_thread() {
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(), PORT));

{
boost::asio::ip::tcp::socket socket(io_service);
acceptor.accept(socket);

boost::asio::streambuf sb;
boost::system::error_code ec;
while (boost::asio::read(socket, sb, ec)) {
std::cout << "received: '" << &sb << "'\n";

if (ec) {
std::cout << "status: " << ec.message() << "\n";
break;
}
}
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
}
}

#include <boost/thread.hpp>

int main() {
boost::thread_group tg;
tg.create_thread(server_thread);

boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
tg.create_thread(client_thread);

tg.join_all();
}

关于Boost asio发送和接收消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27672591/

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