C++:一个客户端与多个服务器通信

C++: One client communicating with multiple server

本文关键字:服务器 通信 客户端 C++ 一个      更新时间:2023-10-16

我想知道,是否可以让一个客户端同时与多个服务器通信。据我所知,像火狐这样的常见浏览器正是这样做的。

我现在遇到的问题是,客户端必须侦听并等待来自服务器的数据,而不是请求它本身。它必须一次侦听多个服务器。这可能吗?如果客户端正在侦听服务器 1 并且服务器 2 发送内容,会发生什么情况?包裹是丢失还是会重新发送,直到客户端传达成功接收?使用的协议是TCP。

编辑:平台是Windows。感谢您指出这一点 阿伦穆.

这与使用 select/poll/epoll 或使用线程池或使用每个连接的进程或您所知道的任何模型的常规套接字编程没有什么不同。
我可以向您展示有关如何使用 epoll 执行此操作的粗略伪代码。注意:我的函数都不存在C++,它只是为了解释目的。我也假设你在Linux上,因为你没有提到这个平台。

socket sd = connect("server.com", 8080);
sd.set_nonblocking(1);
epoll_event event;
event.data.fd = sd
epoll_ctl(ADD, event);
...
...
while (True) {
  auto n = epoll_wait(events, 1);
  for (int i : 1...n) {
    if (events[i].data.fd == sd) // The socket added in epoll_ctl
    {
      std::thread(&Session::read_handler, rd_hndler_, sd); // Call the read in another thread or same thread
    }
  }
}

我希望你明白了要点。从本质上讲,将服务器视为客户端,将客户端视为服务器,您的问题就解决了(有点)。查看下面的链接以了解有关epoll
的更多信息https://banu.com/blog/2/how-to-use-epoll-a-complete-example-in-c/

要查看使用 epoll 的全功能服务器设计,请查看:
https://github.com/arun11299/cpp-reactor-server/blob/master/epoll/reactor.cc