Example #1
0
void MMyLib::MyClient::conn_handler(const system::error_code& ec, sock_pt sock)
{
	if(ec)
		return;
	cout<< "recive from "<< sock->remote_endpoint().address()<< endl;
	std::shared_ptr<vector<char> > str(new vector<char>(100, 0));

	sock->async_read_some(buffer(*str), boost::bind(&MyClient::read_handler, this, boost::asio::placeholders::error, str));
}
Example #2
0
void MMyLib::MyServer::accept_handler(const boost::system::error_code& ec, sock_pt sock)
{
	if(ec)
		return ;
	cout<< "MyClients:";
	cout<< sock->remote_endpoint().address()<< endl;
	sock->async_write_some(buffer("hello asio"), \
		boost::bind(&MyServer::write_handler, this, boost::asio::placeholders::error));
	start();
}
	//当有TCP连接发生时,server::accept_handler()函数将被调用,它使用socket对象发送数据。
	void accept_handler(const boost::system::error_code& ec, sock_pt sock)
	{
		if (ec)//检测错误码
		{
			return;
		}
		//输出连接的客户端信息
		std::cout << "client:";
		std::cout << sock->remote_endpoint().address() << " port:" << sock->remote_endpoint().port() << std::endl;
		
		sock->async_write_some(boost::asio::buffer("hello asio"), bind(&server::write_handler, this, boost::asio::placeholders::error));
		
		//再次启动异步接受连接
		//首先它必须检测asio传递的error_code,保证没有错误发生。
		//然后调用socket对象的async_write_some()异步发送数据。
		//同样,我们必须再为这个异步调用编写回调函数write_handler()。
		//当发送完数据后不要忘了调用start()再次启动服务器接收连接,否则当完成数据发送后io_service将因为没有时间处理而结束运行。
		start();
				
	}
Example #4
0
void CRecvMsg::accept_handler(const boost::system::error_code& ec,sock_pt sock)
{
	if(ec)
	{
		ip=sock->remote_endpoint().address().to_string();
		std::string message=ip+" "+numToStr(port)+"连接异常";
		writeLog(message,es);
		return;
	}

	start();

	ip=sock->remote_endpoint().address().to_string();

	QString content=tr("已连接");
	QString relateDevice=QString("%1 %2").arg(ip.c_str()).arg(port);
	idR->insertLog(relateDevice,content);
	
	std::string message=ip+" "+numToStr(port)+"已连接";
	writeLog(message,es);

	try{
		sock->async_read_some(boost::asio::buffer(pRecvBuff, 1024),
			bind(&CRecvMsg::read_handler, this,
			placeholders::error,
			placeholders::bytes_transferred,sock));

		//boost::posix_time::time_duration td(0,0,2,0);
		//boost::this_thread::sleep(td);
	}
	catch (std::exception& e)   
	{   
		//std::cerr << "Exception: " << e.what() << "/n";   
		std::string message=ip+" "+numToStr(port)+" "+e.what();
		writeLog(message,es);
	}
}