【发布时间】:2010-02-02 01:24:05
【问题描述】:
我刚刚浏览了 Beej 的网络指南,并对这部分代码感到好奇(特别标有“从这里”和“到这里”):
// main loop
for(;;) {
read_fds = master; // copy it
if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) {
perror("select");
exit(4);
}
// run through the existing connections looking for data to read
for(i = 0; i <= fdmax; i++) {
if (FD_ISSET(i, &read_fds)) { // we got one!!
if (i == listener) {
// handle new connections
addrlen = sizeof remoteaddr;
newfd = accept(listener,
(struct sockaddr *)&remoteaddr,
&addrlen);
if (newfd == -1) {
perror("accept");
} else {
FD_SET(newfd, &master); // add to master set
if (newfd > fdmax) { // keep track of the max
fdmax = newfd;
}
printf("selectserver: new connection from %s on "
"socket %d\n",
inet_ntop(remoteaddr.ss_family,
get_in_addr((struct sockaddr*)&remoteaddr),
remoteIP, INET6_ADDRSTRLEN),
newfd);
}
} else {
// handle data from a client
//----------------- FROM HERE --------------------------
if ((nbytes = recv(i, buf, sizeof buf, 0)) <= 0) {
// got error or connection closed by client
if (nbytes == 0) {
// connection closed
printf("selectserver: socket %d hung up\n", i);
} else {
perror("recv");
}
close(i); // bye!
FD_CLR(i, &master); // remove from master set
//----------------- TO HERE ----------------------------
} else {
// we got some data from a client
for(j = 0; j <= fdmax; j++) {
// send to everyone!
if (FD_ISSET(j, &master)) {
// except the listener and ourselves
if (j != listener && j != i) {
if (send(j, buf, nbytes, 0) == -1) {
perror("send");
}
}
}
}
}
} // END handle data from client
} // END got new incoming connection
} // END looping through file descriptors
} // END for(;;)--and you thought it would never end!
return 0;
现在我知道 read 并不总是读取要在套接字上读取的“所有内容”,并且有时只能返回其中的一部分。在那种情况下,这段代码不会不正确吗?我的意思是,读完之后,连接就被关闭了……相反,我们不应该有一些其他的机制吗?如果是这样,这里的正确方法是什么?
【问题讨论】:
-
我几天前阅读的另一个教程似乎有同样的问题 (ibm.com/developerworks/systems/library/es-nweb/sidefile1.html)。请注意它“一次性”读取请求的部分。
-
有趣.. 一次性逻辑中的确切读取... 我认为当我们想要支持 PUT 命令时,这确实是一个问题。然后我们需要先解析出headers,然后再决定是否要关闭连接。
-
仔细阅读,ThePosey 是对的。套接字仅在出错时关闭。
-
是的......我错了......我太仓促了,并没有真正专注于那里的其他条件...... :)
标签: c networking sockets select