1

我有一些POSIXC要移植到 Windows (WinSocks 2.2) 的代码,并且我在 (not only) 的 MS 实现方面遇到了问题poll()

我对 POSIX 有一些经验sockets,但我对 WinSock2 很陌生,我在 MSDN 上没有找到任何有用的线索,所以我在这里问:“如何在 Windows 上做出与此示例代码相同的行为?”

static int connect_to_addr(char *address, char *port)
{
    struct addrinfo hints;
    struct addrinfo *addr;
    int fd;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = PF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_NUMERICHOST;

    if (getaddrinfo(address, port, &hints, &addr) != 0) return -1;

    fd = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
    if (fd < 0) return -1;

    if (connect(fd, addr->ai_addr, addr->ai_addrlen) < 0) return -1;

    freeaddrinfo(addr);
    return fd;
}

函数connect_to_addr()只是为了演示fd第二个字段的样子。

WSAStartup(...)
...
pollfd cinfd[2];
fds[0].fd = _fileno(stdin); //THIS is probably not supported on win32 
fds[0].events = POLLIN;
fds[1].fd = f_connect(some_addr, some_port); //OK
fds[1].events = POLLIN;

while (1) {
    res = WSAPoll(fds, 2, -1); //returns 1

    if (fds[0].revents & (POLLIN | POLLHUP)) { //fds[0].revents == POLLNVAL  !! problem
        char buf[1024];
        int n, w, i;
        n = read(fds[0].fd, buf, 1024);
        ...
    }

    if (fds[1].revents & POLLIN) {
        char buf[1024];
        int n, w, i;
        n = recv(fds[1].fd, buf, 1024, 0);
        ...
    }
}

WinSocks下如何实现这个常用习语?感谢您的建议。

更好的是,WSAPoll() 从 Vista 开始就在 ws2_32.dll 中;如何让它在XP下工作?

4

1 回答 1

0

你最好使用 WaitForMultipleObjects() 来等待标准输入/袜子。

HANDLE h[2];
h[0] = GetStdHandle(STD_INPUT_HANDLE);
h[1] = sock;

while (1) {
    DWORD ret;
    ret = WaitForMultipleObjects(2, h, FALSE, 0 /* wait value you want */);

    if (ret == WAIT_OBJECT_0) {
        // munipulating stdin.
    }
    if (ret == WAIT_OBJECT_0 + 1) {
        // munipulating sock.
        // then call recv.
    }
}
于 2011-06-21T06:04:43.517 回答