我正在尝试使用 Boost 开发一个简单的聊天程序。我遇到了奇怪的情况。在运行发送简单文本的程序时,我使用 netcat 侦听特定端口。连接已建立,但文本混乱。实际上,我有时会得到一两个随机字符而不是整行。我把代码放在下面:
#include "lib/client.h"
#include <boost/asio.hpp>
#include <boost/asio/io_service.hpp>
#include <iostream>
#include <thread>
#include <string>
int main(int argc, char* argv[]){
if(argc != 3){
std::cout << "Wrong use. After specifying executable, add host and port\n";
return 0;
}
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver(io_service);
auto endpoint = resolver.resolve({argv[1],argv[2]});
Client c(io_service, endpoint);
std::thread t([&io_service](){ io_service.run();});
std::string text = "Welcome host!";
c.add_msg_to_deque(text);
t.join();
c.close();
return 0;
}
这是客户端方法:
#include "../lib/client.h"
#include <boost/asio.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/array.hpp>
#include <deque>
#include <iostream>
#include <string>
void Client::connect(boost::asio::ip::tcp::resolver::iterator endpoint){
boost::asio::async_connect(socket, endpoint,
[this](boost::system::error_code ec, boost::asio::ip::tcp::resolver::iterator)
{
if (!ec)
{
}
});
}
void Client::close()
{
ios.post([this]() { socket.close(); });
}
void Client::add_msg_to_deque(const std::string& msg){
ios.post([this,msg](){
write_msg_deque.push_back(msg);
send_msg();
});
}
void Client::send_msg(){
boost::array<char,128> buf;
std::string temp_string = write_msg_deque.front();
std::copy(temp_string.begin(),temp_string.end(),buf.begin());
boost::asio::async_write(socket, boost::asio::buffer(buf,temp_string.size()),[this](boost::system::error_code ec, std::size_t){
if(!ec){
write_msg_deque.pop_front();
if(!write_msg_deque.empty())
send_msg();
}
else{
socket.close();
}
});
}
您正在使用async_write
本地数据,这是个坏主意。async_write
立即返回。调用async_write
您的方法后send_msg
终止,因此buf
在发送消息之前销毁本地数据(数组)。您可以使用 IO 函数的同步版本来发送数据或buf
作为类的成员保留以提供数据,直到数据成功发送。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句