如何使用标准库网络 TS 在服务器和客户端之间发送消息C++

How to Send messages between server and client using C++ standard library networking TS

本文关键字:之间 客户端 C++ 消息 服务器 标准 何使用 网络 TS      更新时间:2023-10-16

我已经尝试按照boost中的教程进行操作,但是API并不相同,所以我不得不猜测某些部分。

到目前为止,我的尝试如下所示:

#include <iostream>
#include <experimental/internet>
#include <experimental/socket>
#include <thread>
#include <chrono>
using namespace std::experimental;
int main(int argc, char* argv[])
{
std::thread server = std::thread([]()
{
std::cout << "Starting server" << std::endl;
net::io_context context;
net::ip::tcp::endpoint endpoint{net::ip::tcp::v4(), 1234};
net::ip::tcp::acceptor acceptor{context, endpoint};
acceptor.non_blocking(true);
std::cout << "opened server on " << endpoint << std::endl;
std::error_code error;
net::ip::tcp::socket socket(context);
while (true)
{
socket = acceptor.accept(error); //accept connections
if (!error) //if connected with a client
{
std::cout << "Connected to client!" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
std::string data = "Hello World!";
net::const_buffer buf(&data, sizeof(data));
socket.send(buf);
std::cout << "Sent data!" << std::endl;
while(true) {}
}
}
});

std::thread client = std::thread([]()
{
net::io_context context;
net::ip::tcp::socket socket(context);
net::ip::tcp::endpoint server{net::ip::tcp::v4(), 1234};
std::error_code error;
while(true)
{
socket.connect(server, error); //attempt to connect
if (!error) //if connected
{
std::cout << "Connected to server!" << std::endl;
net::mutable_buffer buf;
while(buf.size() == 0)
{
socket.receive(buf);
}
std::cout << "Received data!" << std::endl;
std::cout << buf.data() << std::endl;
while(true) {}
}
}
});
server.join();
return 0;
}

服务器和客户端连接,但客户端未收到消息。上面程序的输出是:

Starting server
opened server on 0.0.0.0:1234
Connected to server!
Connected to client!
Sent data!

然后它永远等待。

如何让套接字正确接收数据?

这个

std::string data = "Hello World!";
net::const_buffer buf(&data, sizeof(data));

是错误的。您希望发送字符串data内容,而不是其内部字节。&data为您提供指向字符串实例的基础数据的指针,而不是其内容。如果要创建表示data内容的缓冲区,可以执行以下操作:

const std::string data = "Hello World!";
net::const_buffer buf = net::buffer(data);

net::mutable_buffer buf;
while(buf.size() == 0)
{
socket.receive(buf);
}

为您提供无限循环,因为buf的初始大小为 0,因此receive读取 0 字节并返回。然后,在检查条件时,buf 的大小仍为 0,循环继续。

在调用receive之前,您需要指定缓冲区的大小 - 它指示必须读取多少字节。您正在发送Hello World!

std::string msg;
msg.resize(12); // prepare space for incoming data
net::mutable_buffer buf = net::buffer(msg);
socket.receive(buf);
std::cout << "I got: " << msg << std::endl;