网络传输 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)            
}

  

posted on 2017-08-15 14:02  itdef  阅读(317)  评论(2编辑  收藏  举报

导航