了解是否接受套接字



我有使用poll()方法的基本示例:

struct pollfds fds[5];
int nfds = 1;
fds[0].fd = listen_sd;
fds[0].events = POLLIN;
while(1) {
int ret = poll(fds, nfds, 0);
if (ret < 0) {
exit(1);
}
int size = nfds;
for (int i = 0; i < size; i++) {
if (fds[i].revents == 0) {
continue;
}
if (fds[i].revents != POLLIN) {
exit(1);
}
if (fds[i].fd == listen_sd) {
// Something happened on the server
// If there is a client which wasn't accepted yet, it returns its fd
int new = accept(listen_sd, null, null);
// If there is a client which was already accepted,
// it doesn't return anything, just loop in accept() method
} else {
// Something happened on a different socket than the server
}
}
}

来自客户端的所有消息都将流经服务器套接字。

这意味着服务器套接字上总是发生了一些事情,不是吗?

但是我怎么能做这样的事情(在真实条件下(:

  • 尝试接受套接字,应该返回一些函数:套接字已经 已接受,套接字尚未接受。

  • 当套接字已被接受时 - 接收数据。

  • 当套接字尚未被接受时 - 接受套接字和 接收数据。

在服务器端,侦听连接的 TCP 套接字在客户端连接等待被接受时将进入可读状态。 调用accept()以实际接受连接,然后您可以开始监视accept()返回的新 TCP 套接字上的读/写/关闭状态。 这是一个与侦听连接的套接字完全分开的套接字。 将其添加到pollfds数组中,以便可以同时轮询它和侦听套接字。

尝试这样的事情:

#include <vector>
std::vector<pollfds> fds;
{
pollfds listen_pf;
listen_pf.fd = listen_sd;
listen_pf.events = POLLIN;
listen_pf.push_back(listen_pf);
}
while (true) {
int ret = poll(fds.data(), fds.size(), 0);
if (ret < 0) {
exit(1);
}
size_t i = 0, size = fds.size();
while (i < size) {
if (fds[i].revents & POLLIN) {
if (fds[i].fd == listen_sd) {
// accept a pending client connection...
int client_sd = accept(listen_sd, NULL, NULL);
if (client_sd != -1) {
pollfds client_pf;
client_pf.fd = client_sd;
client_pf.events = POLLIN | POLLOUT | POLLRDHUP;
fds.push_back(client_pf);
}
}
else {
// read data from fds[i].fd as needed...
if (read fails) {
fds.erase(fds.begin()+i);
--size;
continue;
}
}
}
if (fds[i].revents & POLLOUT) {
// write pending data to fds[i].fd as needed ...
if (write fails) {
fds.erase(fds.begin()+i);
--size;
continue;
}
}
if (fds[i].revents & (POLLERR | POLLHUP | POLLNVAL)) {
if (fds[i].fd == listen_fd) {
exit(1);
}
else {
fds.erase(fds.begin()+i);
--size;
continue;
}
}
++i;
}
}

在客户端,当connect()成功并且已与服务器完全建立连接并准备好进行 I/O 时,连接到服务器的 TCP 套接字将进入可写状态。

最新更新