C++:一个客户端与多个服务器通信
C++: One client communicating with multiple server
我想知道,是否可以让一个客户端同时与多个服务器通信。据我所知,常见的浏览器,例如 firefox 就是这样做的。
我现在遇到的问题是,客户端必须监听并等待来自服务器的数据,而不是自己请求数据。它必须同时监听多个服务器。这可能吗?如果客户端正在监听服务器 1 而服务器 2 发送了一些东西,会发生什么?包裹丢失还是会重新发送,直到客户传达成功接收?使用的协议是TCP。
编辑:平台是 Windows。感谢阿润木指出这一点。
这与使用 select/poll/epoll 或使用线程池或使用每个连接的进程或您知道的任何模型的常规套接字编程没有什么不同。
我可以向您展示一个关于如何使用 epoll 执行此操作的粗略伪代码。
注意:None 我的函数存在于 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
}
}
}
我希望你明白了要点。本质上,将服务器视为客户端,将客户端视为服务器,您的问题就解决了(某种程度上)。查看下面 link 了解更多关于 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
我想知道,是否可以让一个客户端同时与多个服务器通信。据我所知,常见的浏览器,例如 firefox 就是这样做的。
我现在遇到的问题是,客户端必须监听并等待来自服务器的数据,而不是自己请求数据。它必须同时监听多个服务器。这可能吗?如果客户端正在监听服务器 1 而服务器 2 发送了一些东西,会发生什么?包裹丢失还是会重新发送,直到客户传达成功接收?使用的协议是TCP。
编辑:平台是 Windows。感谢阿润木指出这一点。
这与使用 select/poll/epoll 或使用线程池或使用每个连接的进程或您知道的任何模型的常规套接字编程没有什么不同。
我可以向您展示一个关于如何使用 epoll 执行此操作的粗略伪代码。
注意:None 我的函数存在于 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
}
}
}
我希望你明白了要点。本质上,将服务器视为客户端,将客户端视为服务器,您的问题就解决了(某种程度上)。查看下面 link 了解更多关于 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