代码之家  ›  专栏  ›  技术社区  ›  ChrisInEdmonton

简单C/C++网络I/O库

  •  1
  • ChrisInEdmonton  · 技术社区  · 16 年前

    使用阻塞套接字的天真方法不起作用;偶尔,我会有一个线程卡在“连接”中。我不能使用SIGALRM,因为我正在使用pthreads。我尝试将代码转换为O_NONBLOCK,但这使读取单行代码变得非常复杂。

    我有什么选择?我正在寻找允许以下伪代码的最简单解决方案:

    
    // Inside a pthread
    try {
        req = connect(host, port);
        req.writeln("request command");
        while (line = req.readline()) {
            // Process line
        }
    } catch TimeoutError {
        // Bitch and complain
    }
    

    我的代码是C++,我使用Boost。快速浏览 Boost ASIO ACE 太重了,解决不了这个问题。

    4 回复  |  直到 16 年前
        1
  •  6
  •   ZZ Coder    16 年前

    你看过libevent吗?

    http://www.monkey.org/~provos/libevent/

    这是完全不同的模式,但性能是如此惊人。

    memcached构建在libevent之上。

        2
  •  5
  •   coelhudo    16 年前

    我看到了这些评论,我认为您可以将boost::asio与boost::asio::deadline\u计时器一起使用

    代码片段:

        void restart_timer()
        {
           timer_.cancel();
           timer_.expires_from_now(boost::posix_time::seconds(5));
           timer_.async_wait(boost::bind(&handleTimeout,
           MyClass::shared_from_this(), boost::asio::placeholders::error));
        }
    

    timer_ 是boost::asio::deadline\u计时器吗 MyClass与

        class Y: public enable_shared_from_this<Y>
        {
         public:
    
         shared_ptr<Y> f()
         {
           return shared_from_this();
         }
        }
    

    在连接ou读/写之前,可以调用restart_timer

    更多 information 关于 share_from_this()

        3
  •  1
  •   user224579    16 年前

    你提到这种情况“非常偶然”。你的“连接”端应该有你正在寻找的容错和错误处理,但是你也应该考虑服务器、DNS、网络连接等的稳定性。

        4
  •  0
  •   Norman    16 年前

    您也可以从另一个线程关闭套接字。这将导致连接失败。