如何从boostudp服务器读取数据
这是接收数据并打印数据的UDP服务器的代码 我可以接收消息,但在消息的结尾,我也得到了一些垃圾字符 我只想显示实际发送的消息,最后不显示垃圾字符 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////如何从boostudp服务器读取数据,boost,udp,boost-asio,Boost,Udp,Boost Asio,这是接收数据并打印数据的UDP服务器的代码 我可以接收消息,但在消息的结尾,我也得到了一些垃圾字符 我只想显示实际发送的消息,最后不显示垃圾字符 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include <string> #include <ios
#pragma once
#include <string>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/array.hpp>
#include <qdebug.h>
using boost::asio::ip::udp;
class udp_server
{
public:
udp_server(boost::asio::io_service& io_service)
: socket_(io_service, udp::endpoint(udp::v4(), 13))
{
start_receive();
}
private:
void start_receive()
{
socket_.async_receive_from(
boost::asio::buffer(recv_buffer_), remote_endpoint_,
boost::bind(&udp_server::handle_receive, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void handle_receive(const boost::system::error_code& error,
std::size_t /*bytes_transferred*/)
{
if (!error || error == boost::asio::error::message_size)
{
std::string str(recv_buffer_.c_array());
std::cout << str; // Printing the string shows junk characters also
boost::shared_ptr<std::string> message(
new std::string("WAVEFRONT"));
socket_.async_send_to(boost::asio::buffer(*message), remote_endpoint_,
boost::bind(&udp_server::handle_send, this, message,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
start_receive();
}
}
void handle_send(boost::shared_ptr<std::string> /*message*/,
const boost::system::error_code& /*error*/,
std::size_t /*bytes_transferred*/)
{
}
udp::socket socket_;
udp::endpoint remote_endpoint_;
boost::array< char, 256> recv_buffer_;
};
#pragma一次
#包括
#包括
#包括
#包括
#包括
#包括
使用boost::asio::ip::udp;
类udp_服务器
{
公众:
udp_服务器(boost::asio::io_服务和io_服务)
:套接字(io_服务,udp::端点(udp::v4(),13))
{
开始接收();
}
私人:
无效开始\接收()
{
套接字异步接收来自(
boost::asio::buffer(recv_buffer_uu)、remote_endpoint_uu、,
boost::bind(&udp_服务器::handle_receive,这个,
boost::asio::占位符::错误,
boost::asio::占位符::字节(已传输);
}
无效句柄接收(常量boost::system::error\u代码和错误,
std::大小\u t/*字节\u传输*/)
{
如果(!error | | error==boost::asio::error::message|u size)
{
string str(recv_buffer_u.c_array());
标准::cout recv_buffer_;
};
“最后的垃圾字符”是接收asio
的UDP数据之后的接收缓冲区中的字符
您在handle\u receive
函数中注释掉的bytes\u transfered
参数告诉您实际接收了多少字符asio
,即