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驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    C# WebSocket 实现客户端和服务端的通信(二)
    C# WebSocket 实现客户端和服务端的通信(一)
    regsvr32 将dll写入注册表
    Dictionary 添加重复的键值对
    C# Math.Round()的银行家算法
    DataGridView 合并数据相同的行
    获取系统当前日期,分布获取年月日和时分秒
    [Err] ORA-00923: 未找到要求的 FROM 关键字
    正则表达式常用的字符类
    Spring注解作用
  • 原文地址:https://www.cnblogs.com/itdef/p/7364738.html
Copyright © 2011-2022 走看看