灰常简单的代码,就不多解释了,我这里用的VSPD虚拟的串口做的测试。
server:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
void handle_read(boost::asio::serial_port& port,const boost::system::error_code& ec,size_t byte_read);
char data[1024];
void handle_write(boost::asio::serial_port& port,const boost::system::error_code& ec)
{
if (ec)
{
std::cout<<"异步向串口写入数据失败,错误原因:"<<ec.message()<<std::endl;
return;
}
port.async_read_some(boost::asio::buffer(data),
boost::bind(handle_read,boost::ref(port),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void handle_read(boost::asio::serial_port& port,const boost::system::error_code& ec,size_t byte_read)
{
if (ec)
{
std::cout<<"异步从串口读入数据失败,错误原因:"<<ec.message()<<std::endl;
return;
}
std::cout<<"收到数据:"<<data<<std::endl;
boost::asio::async_write(port,boost::asio::buffer(data,byte_read),
boost::bind(handle_write,boost::ref(port),
boost::asio::placeholders::error));
}
int main(int argc, char* argv[])
{
boost::asio::io_service ios;
boost::asio::serial_port port(ios);
boost::system::error_code ec;
port.open("COM1",ec);
port.set_option(boost::asio::serial_port::baud_rate(38400)); //波特率
port.set_option(boost::asio::serial_port::flow_control()); //流控制
port.set_option(boost::asio::serial_port::parity()); //奇偶校验
port.set_option(boost::asio::serial_port::stop_bits()); //停止位
port.set_option(boost::asio::serial_port::character_size(8));// 通信字节位数,4—8
if (ec)
{
std::cout<<"打开指定的串口失败,错误原因:"<<ec.message()<<std::endl;
return 1;
}
port.async_read_some(boost::asio::buffer(data),
boost::bind(handle_read,boost::ref(port),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
ios.run();
return 0;
}
client:
#include <boost/asio.hpp>
#include <iostream>
int main(int argc, char* argv[])
{
boost::asio::io_service ios;
boost::asio::serial_port port(ios);
boost::system::error_code ec;
port.open("COM2",ec);
port.set_option(boost::asio::serial_port::baud_rate(38400)); //波特率
port.set_option(boost::asio::serial_port::flow_control()); //流控制
port.set_option(boost::asio::serial_port::parity()); //奇偶校验
port.set_option(boost::asio::serial_port::stop_bits()); //停止位
port.set_option(boost::asio::serial_port::character_size(8));// 通信字节位数,4—8
if (ec)
{
std::cout<<"打开指定的串口失败,错误原因:"<<ec.message()<<std::endl;
return 1;
}
std::string line;
for (;;)
{
std::cin>>line;
boost::asio::write(port,boost::asio::buffer(line.c_str(),line.size()+1),ec);
if (ec)
{
std::cout<<"同步向串口写入数据失败,错误原因:"<<ec.message()<<std::endl;
return 1;
}
char recv_data[100];
boost::asio::read(port,boost::asio::buffer(recv_data,line.size()+1),ec);
if (ec)
{
std::cout<<"同步从串口读入数据失败,错误原因:"<<ec.message()<<std::endl;
return 1;
}
std::cout<<recv_data<<std::endl;
}
return 0;
}
运行效果: