我目前正在管理一個可以同時為最多 MAX_CLIENTS 個客戶端提供服務的服務器。
這是我到目前為止寫的代碼:
//create and bind listen_socket_
struct pollfd poll_fds_[MAX_CLIENTS];
for (auto& poll_fd: poll_fds_)
{
poll_fd.fd = -1;
}
listen(listen_socket_, MAX_CLIENTS);
poll_fds_[0].fd = listen_socket_;
poll_fds_[0].events = POLLIN;
while (enabled)
{
const int result = poll(poll_fds_, MAX_CLIENTS, DEFAULT_TIMEOUT);
if (result == 0)
{
continue;
}
else if (result < 0)
{
// throw error
}
else
{
for (auto& poll_fd: poll_fds_)
{
if (poll_fd.revents == 0)
{
continue;
}
else if (poll_fd.revents != POLLIN)
{
// throw error
}
else if (poll_fd.fd == listen_socket_)
{
int new_socket = accept(listen_socket_, nullptr, nullptr);
if (new_socket < 0)
{
// throw error
}
else
{
for (auto& poll_fd: poll_fds_)
{
if (poll_fd.fd == -1)
{
poll_fd.fd = new_socket;
poll_fd.events = POLLIN;
break;
}
}
}
}
else
{
// serve connection
}
}
}
}
一切都很好,當客戶端關閉其一側的套接字時,一切都得到了很好的處理。
我面臨的問題是,當客戶端連接并發送請求時,如果它之后沒有關閉其一側的套接字,我不會檢測到它并使該套接字“忙碌”。
有沒有辦法實作一個系統來檢測某個時間后套接字上是否沒有收到任何內容?通過這種方式,我可以在服務器端釋放該連接,為新客戶端留出空間。
提前致謝。
uj5u.com熱心網友回復:
當客戶端在特定時間內沒有發送任何資料時,您可以關閉客戶端連接。
對于每個客戶端,您需要存盤最后一次接收資料的時間。
周期性地,例如當poll()因為超時到期而回傳時,您需要檢查所有客戶端的這個時間。當這個時間來得太久之前,你可以shutdown(SHUT_WR)和close()連接。您需要確定“很久以前”是什么。
如果客戶端沒有任何資料要發送但想保持連接打開,它可以定期發送“ping”訊息。服務器可以回復“pong”訊息。這些只是沒有實際資料的小訊息。您是否可以實作此功能取決于您的客戶端/服務器協議。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/416584.html
標籤:
