我有一些POSIX
C
代码,我正在移植到Windows(WinSocks 2.2)并且我遇到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下工作?
答案 0 :(得分:0)
最好使用WaitForMultipleObjects()来等待stdin / sock。
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.
}
}