void CUIServer::Accept_handler(sock_pt sock) { if(m_bConnect) { //only save one connection Accept(); return; } m_socket = sock; m_bConnect = true; Object obj; if (CUIServer::IsInitalEnd == true) { obj.push_back(Pair("type", "init")); obj.push_back(Pair("msg", "initialize end")); } else { obj.push_back(Pair("type", "hello")); obj.push_back(Pair("msg", "hello asio")); } Accept(); string sendData = write_string(Value(std::move(obj)),true); PackageData(sendData); sock->async_write_some(asio::buffer(sendData), bind(&CUIServer::write_handler, this)); std::shared_ptr<vector<char> > str(new vector<char>(100, 0)); memset(data_,0,max_length); sock->async_read_some(asio::buffer(data_,max_length), bind(&CUIServer::read_handler, this, asio::placeholders::error, data_, sock)); }
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(); }