现在的位置: 首页 > 综合 > 正文

Boost 上TCP客户端或者服务器端一种方便的写法

2014年01月09日 ⁄ 综合 ⁄ 共 1577字 ⁄ 字号 评论关闭

class Class_Raw_Retrans
{
public:
	Class_Raw_Retrans(boost::asio::io_service& io_service,ip::tcp::endpoint endpoint)
	:iosev(io_service),
	 socket(iosev),
	 ep(endpoint)
	{
		socket.connect(ep,ec);
		if(ec)
		{
			std::cout << boost::system::system_error(ec).what() << std::endl;
		}
		else
		{
			cout<<" Connection Success! "<<endl;
			Raw_MSG_Retrans();
		}

	}
	void WriteHandle( const boost::system::error_code& error, // Result of operation.
					  std::size_t bytes_transferred )
	{
		if(!error)
		{
			cout<<endl<<" WriteComplete!"<<" Data: "<<"zchx"<<endl<<endl;
		}
	}
	void Raw_MSG_Retrans()
	{
		printf("Raw MSG To be translate\n");
		ASYNC_Write(Message);
	}
	void ASYNC_Write(string buff)
	{

		socket.async_send(buffer(buff),boost::bind(&Class_Raw_Retrans::WriteHandle,this,
			boost::asio::placeholders::error,
			  boost::asio::placeholders::bytes_transferred));
	}

	io_service &iosev;
	ip::tcp::socket socket ;
	ip::tcp::endpoint ep ;
	boost::system::error_code ec;
};

void TCP_Send_Data()
{
	if(statebuffer.TCP_Enable==1 && statebuffer.TCP_destination_Defined==1)
	{
		main_TCP_Server();
	}
}

int main_Raw_Retrans()
{

	io_service iosev;
	stringstream stream ; uint port_buffer ;
	stream<<statebuffer.TCP_destination_port;
	stream>>port_buffer ;

	ip::tcp::endpoint ep(ip::address_v4::from_string(statebuffer.Raw_Retranslation_Addr),60000);
	Class_Raw_Retrans tcp_client(iosev,ep) ;

	iosev.run();

	return 1 ;
}

头文件

#ifndef PUBLIC_HPP
#define PUBLIC_HPP

#include <iostream>
#include <stdio.h>
#include <time.h>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>
#include <string>
#include <unistd.h>

    #define  uchar unsigned char
    #define  uint unsigned int

	using namespace std ;
	using boost::asio::ip::udp;
	using boost::asio::ip::tcp;
	using namespace boost::asio;



#endif

【上篇】
【下篇】

抱歉!评论已关闭.