网络传输 buf 封装 示例代码
网络传输 buf 封装 示例代码
使用boost库 asio
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | // BufferWrapTest.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "BufStruct.h" #include <ctime> #include <iostream> #include <string> #include <boost/asio.hpp> using boost::asio::ip::tcp; DEF::BufferStruct make_message() { using namespace DEF; // For time_t, time and ctime; BufferHead bh( '|' ,strlen( "hello world!" )); BufferStruct bs; bs.head = bh; memcpy( bs.bufBody, "hello world!" , bh.bufferLenth); return bs; } int main() { try { boost::asio::io_service io_service; tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 9013)); for (;;) { tcp::socket socket(io_service); acceptor.accept(socket); DEF::BufferStruct message = make_message(); boost::system::error_code ignored_error; boost::asio::write(socket, boost::asio::buffer(&message,message.GetLength()+ sizeof (DEF::BufferHead)), ignored_error); } } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #pragma once #include <string> #include <memory> #include <iostream> namespace DEF { const int BUF_MAX_LENTH = 1024 * 1; const char MAGIC_CHAR = '|' ; #pragma pack (push,1) struct BufferHead { char flag; // should equal '|' unsigned int bufferLenth; BufferHead() { flag = 0; bufferLenth = 0; } BufferHead( char f, unsigned int len) { flag = f; bufferLenth = len; } }; struct BufferStruct { BufferHead head; char bufBody[BUF_MAX_LENTH]; BufferStruct() {} BufferStruct( const BufferStruct& b) { head = b.head; memcpy(bufBody, b.bufBody, b.head.bufferLenth); } char * GetBody() { return bufBody; } unsigned int GetLength() { return head.bufferLenth; } }; #pragma pack(pop) } |
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力


【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2016-08-15 CMAKE 教程前两章节学习