首页 技术 正文
技术 2022年11月15日
0 收藏 675 点赞 4,852 浏览 1758 个字

因为TCP是流式处理的,所以包没有边界,必须设计一个包头,里面表示包的长度(一般用字节表示),根据这个来逐个拆包。如果对于发送/接收频率不高的话,一般也就不做拆包处理了,因为不大可能有粘包现象。

以下是粘包和拆包的分析:

http://blog.csdn.net/zhangxinrun/article/details/6721495

用Qt的TCPSocket读出的数据来拆:

http://www.aiuxian.com/article/p-1732805.html

我是根据以上链接例子Qt的逻辑来实现的,用Boost的ASIO来读取,是同步的:

 m_imp->m_thread = boost::make_shared<boost::thread>(
[=]()
{
while (!boost::this_thread::interruption_requested())
{
boost::this_thread::interruption_point(); try
{
boost::system::error_code ec;
std::vector<uint8_t> tmpreadBuffer( * ); size_t bytes_transferred = m_imp->m_sockPtr->read_some(boost::asio::buffer(tmpreadBuffer), ec); std::cout << "Byte Transfered:" << bytes_transferred << "\n"; if (!ec)
{ if (bytes_transferred == ) continue; if (bytes_transferred < MSG_HEAD_SIZE)
{
m_imp->m_readBuffer.insert(m_imp->m_readBuffer.end(), tmpreadBuffer.begin(), tmpreadBuffer.begin() + bytes_transferred / sizeof(uint8_t));
continue;
}
else
{
m_imp->m_readBuffer.insert(m_imp->m_readBuffer.end(), tmpreadBuffer.begin(), tmpreadBuffer.begin() + bytes_transferred / sizeof(uint8_t)); size_t totalSize = m_imp->m_readBuffer.size()*sizeof(uint8_t); while (totalSize)
{
size_t msgSize = m_imp->getMsgLen();
std::cout << "Msg Size is:" << msgSize << "\n"; std::vector<uint8_t>::const_iterator first = m_imp->m_readBuffer.begin();
std::vector<uint8_t>::const_iterator last = m_imp->m_readBuffer.begin() + msgSize / sizeof(uint8_t);
std::vector<uint8_t> tmpMsg(first, last); m_imp->m_msgQueue.push_back(tmpMsg); m_imp->m_readBuffer.erase(first, last); totalSize = m_imp->m_readBuffer.size()*sizeof(uint8_t); } } }
else
{
std::cerr << "recv error : RAC module!" << ec.message() << std::endl;
m_imp->m_sockPtr->close();
break;
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
m_imp->m_sockPtr->close();
break;
}
}
} );

以下一个附带干货,以前一直不太理解Qt的TCPSocket,下面是底层原理:

http://blog.csdn.net/ying_593254979/article/details/17006507

上一篇: docker安装minio
下一篇: epoll实现原理
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,085
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,560
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,409
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,182
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,819
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,902