|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
异步time时间服务器:
一次能连接多个客户端,处理多个客户端的事务
- // 异步time时间服务器:
- #include <boost/asio.hpp>
- //#include <boost\bind.hpp>//老式写法
- #include <iostream>
- #include <string>
- using boost::asio::ip::tcp;
- std::string make_daytime_string()
- {
- using namespace std;//For time_t, time and ctime;
- //time_t now = time(0);
- auto now = time(nullptr);
- return ctime(&now); // 返回const char*
- }
- class tcp_connection : public std::enable_shared_from_this<tcp_connection> {
- public :
- using pointer = std::shared_ptr<tcp_connection>;
- static pointer create(boost::asio::io_service &io_service) {
- //std::make_shared
- return pointer(new tcp_connection(io_service));
- }
- tcp::socket &socket() { return socket_; }
- void start() {
- message_ = make_daytime_string();//返回当前时间
- auto self = shared_from_this();
- #if (0) //老式写法
- boost::asio::async_write(//sync同步,async异步
- socket_, boost::asio::buffer(message_),
- boost::bind(
- &tcp_connection::handle_write,
- shared_from_this(),
- boost::asio::placeholders::error,
- boost::asio::placeholders::bytes_transferred));
- #endif
- boost::asio::async_write(
- socket_, boost::asio::buffer(message_),
- [self = std::move(self)](auto error, auto bytes_transferred){
- self->handle_write(error,bytes_transferred);
- });//用move不用引用是怕失效,同时省略掉一次拷贝
- }
- private:
- tcp_connection(boost::asio::io_service &io_service) : socket_(io_service){}
- void handle_write(const boost::system::error_code & error, size_t bytes_transferred) {
- std::cout << "write succ \n" << std::endl;
- }
- tcp::socket socket_;
- std::string message_;
-
- };
- class tcp_server {
- public:
- tcp_server(boost::asio::io_service &io_service) : acceptor_(io_service, tcp::endpoint(tcp::v4(), 2001)) {// 绑定端口
- start_accept();//等待新连接;
- }
- private:
- void start_accept() {
- //tcp_connection::pointer new_connection
- auto new_connection = tcp_connection::create(acceptor_.get_io_service());
- //异步的方式,开始接受客户端的连接,连接成功或失败进入回调
- #if (0)
- //老式的
- acceptor_.async_accept(new_connection->socket(),
- boost::bind(&tcp_server::handle_accept,
- this, new_connection,
- boost::asio::placeholders::error));
- #endif
- //新式的
- acceptor_.async_accept(new_connection->socket(),
- [this, new_connection](auto error) {
- this->handle_accept(new_connection, error);
- });
- }
- void handle_accept(tcp_connection::pointer new_connection,
- const boost::system::error_code &error) {
- //new_connection是否连接已经成功的connection,error是否已经成功
- if (!error) {
- new_connection->start();
- }
- start_accept();
- }
- tcp::acceptor acceptor_;
- };
- int main()
- {
- // 我们的程序和操作系统底层之间的一个相互传递的枢纽
- // 会把事件按照一定方式进行处理;
- boost::asio::io_service io;
-
- try
- {
-
- tcp_server server(io);
- io.run();
- }
- catch (std::exception &e)
- {
- std::cerr << e.what() << std::endl;
- }
-
- std::cout << "mian finish run \n" << std::endl;// 提示下main函数已经结束了
- system("pause");// 让VS控制台程序不会一闪而过;
- return 0;
- }
复制代码 |
评分
-
查看全部评分
|