2016-05-30 182 views
0

我想知道,如果有可能让一个客户端同时与多个服务器通信。据我所知,像firefox这样的常见浏览器正在这样做。C++:一个客户端与多个服务器通信

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

编辑:平台是Windows。感谢你指出了Arunmu。

回答

0

这与使用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

+0

谢谢。这有帮助。 – YokeM

+0

@YokeM很高兴帮助。 – Arunmu