我刚刚浏览了Beej的网络指南,并对这部分代码感到好奇(特别标有“From here”和“To here”):
// 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并不总是读取要在套接字上读取的“所有内容”,并且它有时只返回部分内容。在这种情况下,这段代码不是不正确吗?我的意思是,在一次阅读之后,连接正在关闭......相反,我们不应该有其他机制吗?如果是这样,这里的正确方法是什么?
答案 0 :(得分:4)
如果recv()发生错误,套接字只会在那里关闭,否则它将处理读取的数据,即使它没有被读取。然后它会在它再次循环时读出更多。很确定这就是你问的问题?
答案 1 :(得分:1)
是的,你会继续阅读,直到你得到你期望的所有数据,显然你需要某种方式知道预期多少 - 这就是为什么http把文档大小放在首位
答案 2 :(得分:1)
当recv()返回负值时,你唯一的调用关闭,这意味着recv有某种错误。请注意,您关闭的块有一条注释// got error or connection closed by client
)。
当您实际获得一些数据时(以// we got some data from a client
开头的else分支),连接未被关闭。
你是对的,你不能假设数据一次全部到达。你的错误在于遵循代码的工作方式。