尝试为一种类似于echo服务器的服务器编写客户端。当我尝试发送东西时,会发出哔哔声。我发现问题出现在win_iocp_socket_service_base.ipp文件的第356行(在我的编辑器上)。代码是:
int result = ::WSASend(impl.socket_, buffers,
static_cast<DWORD>(buffer_count), &bytes_transferred, flags, op, 0);
然后我做了一些研究。
Continuous boost::asio reads在答案的评论中,有人在将二进制数据写入std::cout
时说。
Why does the following code make my computer beep?在这里,似乎问题是一样的。他们得出的结论是&#39; \ a&#39;是产生声音的原因。
调试应用程序,我前面提到的API函数的缓冲区包含以下内容:
"asd@ıııı2•Z\x1aP"
这里&#34; asd @&#34;是我的字符串,每次调试时其余都会改变,我不知道它们是什么。现在,这可能是声音产生的部分,但我的问题是如何防止声音呢?
我有以下一轮实施&#34;对应&#34;功能。请注意,我还有一个独立的Send()
函数实现,可以与ReadUntil()
明确配对,以实现相同的结果。同时使用Send()
和ReadUntil()
,仍会产生哔声。通常,这不应该发生,因为我不处理低级API函数,但Boost.Asio。我做错了吗?
CODES
void Correspond(const std::string &data,
const std::string &delim,
std::vector<char> &response)
{
std::shared_ptr<std::vector<char>> localbuffer = std::make_shared<std::vector<char>>(data.begin(), data.end());
// pass shared_ptr to callback function to prolong the buffer's lifetime
// !!! perhaps a better buffer management is needed
socket.async_send(boost::asio::buffer(*localbuffer),
std::bind(&TCPClient::on_correspond,
this,
std::placeholders::_1,
std::placeholders::_2,
delim,
std::ref(response),
localbuffer));
}
以及以下回调实现
void on_correspond(const boost::system::error_code& errorcode,
std::size_t sent,
const std::string &delim,
std::vector<char> &response,
const std::shared_ptr<std::vector<char>> &buffer)
{
if(errorcode) {
SLOGERROR(mutex, errorcode.message(), "on_correspond()");
}
if(sent == 0) {
SLOG(mutex, "0 bytes sent w/o errors", "on_correspond()");
}
ReadUntil(delim, response);
}
深入调试API后,我发现此问题与读取功能无关,但我会在此发布,以确定。
void ReadUntil(const std::string &delim, std::vector<char> &response)
{
boost::asio::async_read_until(socket,
buffer,
delim,
std::bind(&TCPClient::on_readuntil,
this,
std::placeholders::_1,
std::placeholders::_2,
std::ref(response)));
}
void on_readuntil(const boost::system::error_code& errorcode,
std::size_t received,
std::vector<char> &response)
{
SLOG(mutex, "on_readuntil invoked", "on_readuntil()");
SLOG(mutex, received, "on_readuntil");
// !!! needs error handling, short-read handling and whatnot
if(errorcode) {
SLOGERROR(mutex, errorcode.message(), "on_readuntil()");
return;
}
if(received == 0) {
SLOG(mutex, "0 bytes received w/o errors", "on_readuntil()");
}
response.reserve(received);
std::copy(boost::asio::buffers_begin(buffer.data()),
boost::asio::buffers_begin(buffer.data()) + received,
std::back_inserter(response));
buffer.consume(received);
}
答案 0 :(得分:1)
here "asd@" is my string, the rest changes every time when I debug
读取缓冲区时不关心它的大小,欢迎使用C ++。给boost::asio::buffer
缓冲区大小。