zoukankan      html  css  js  c++  java
  • 网络传输 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驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    (十四)配置的热更新
    (十三)在ASP.NET CORE中使用Options
    (十二)Bind读取配置到C#实例
    【转载】ViewState的用法
    【转载】Web Service和WCF的到底有什么区别
    【转载】小小的公共库,大大的耦合,你痛过吗?
    【转载】ASP.NET应用程序与页面生命周期
    【转载】分布式数据库架构--分库、分表、排序、分页、分组、实现
    【转载】ASP和ASP.NET根本区别
    【转载】聊一聊C#的Equals()和GetHashCode()方法
  • 原文地址:https://www.cnblogs.com/itdef/p/7364738.html
Copyright © 2011-2022 走看看