网络传输 buf 封装 示例代码
网络传输 buf 封装 示例代码
使用boost库 asio
// 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; }
#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驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力