我正要通過網絡指南由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