这是我的boost::asio
服务器
class Server: public boost::enable_shared_from_this<Server>, private boost::noncopyable{
private:
boost::asio::ip::tcp::acceptor _acceptor;
boost::asio::ip::tcp::socket _socket;
public:
explicit Server(boost::asio::io_service& ios, boost::asio::ip::tcp::endpoint& endpoint):_acceptor(ios, endpoint), _socket(ios){
}
void start(){
accept();
}
void accept(){
std::cout << "accepting " << std::endl;;
_acceptor.async_accept(_socket, boost::bind(&Server::handler, this, boost::asio::placeholders::error));
}
void handler(const boost::system::error_code &ec){
const std::string message = "HTTP/1.1 200 OK\r\nContent-Length: 13\r\n\r\nHello, world!";
if(!ec){
boost::asio::async_write(_socket, boost::asio::buffer(message), boost::bind(&Server::write_handler, this));
}else{
std::cout << ec << std::endl;
}
accept();
}
void write_handler(){
}
boost::asio::ip::tcp::socket& socket(){
return _socket;
}
};
int main(){
boost::asio::io_service ios;
const unsigned int port = 5050;
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port);
Server server(ios, endpoint);
server.start();
ios.run();
return 0;
}
它第一次以“你好世界”回应;然后它只是在accept
<-->handler
循环中循环并且不写欢迎消息。ec
印刷
asio.misc:1
accepting
asio.misc:1
accepting
asio.misc:1
accepting
asio.misc:1
accepting
asio.misc:1
accepting
asio.misc:1
accepting
......
并且永不停止