C++中的简单多线程服务器?

gri*_*fin 5 c++ sockets client-server

我想编写一个简单的服务器应用程序,它将从客户端应用程序获取命令并在单独的线程中运行这些命令.

在dlib中查看服务器类.有没有人有使用它的经验?它与使用Boost的Asio相比如何?

Sha*_*ane 4

Boost Asio 可以很轻松地做到这一点。查看Highscore 教程 中的示例,其中展示了如何使用 Boost 进行多线程异步输入/输出。

#include <boost/asio.hpp> 
#include <boost/thread.hpp> 
#include <iostream> 

void handler1(const boost::system::error_code &ec) 
{ 
  std::cout << "5 s." << std::endl; 
} 

void handler2(const boost::system::error_code &ec) 
{ 
  std::cout << "5 s." << std::endl; 
} 

boost::asio::io_service io_service; 

void run() 
{ 
  io_service.run(); 
} 

int main() 
{ 
  boost::asio::deadline_timer timer1(io_service, boost::posix_time::seconds(5)); 
  timer1.async_wait(handler1); 
  boost::asio::deadline_timer timer2(io_service, boost::posix_time::seconds(5)); 
  timer2.async_wait(handler2); 
  boost::thread thread1(run); 
  boost::thread thread2(run); 
  thread1.join(); 
  thread2.join(); 
}
Run Code Online (Sandbox Code Playgroud)