我正要通过网络指南由Beej和很好奇的这部分代码(特别是标有“从这里开始”和“至此”):C:有关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;
现在我知道,阅读没有按” t始终读取要在套接字上读取的“所有内容”,并且它有时只能返回其中的一部分。在这种情况下,这个代码是不是不正确?我的意思是,在一次阅读后,连接正在关闭......相反,我们是不是应该有其他一些机制?如果是这样,这里有什么正确的方法?
我前几天看到的另一个教程似乎有相同的问题(http://www.ibm.com/developerworks/systems/library/es-nweb/sidefile1.html)。请注意它在“一次性”中读取请求的部分。 – 2010-02-02 01:28:59
有趣的..在一次性逻辑中的确切读法......我想如果让我们说要支持PUT命令,那真的会是一个问题。然后,我们需要先解析出标题,然后再决定是否要关闭连接。 – Legend 2010-02-02 01:31:21
仔细阅读,ThePosey是对的。套接字仅在发生错误时关闭。 – 2010-02-02 01:39:36