gpt4 book ai didi

C:关于 Beej 的网络指南的问题......这里有一个假设吗?

转载 作者:行者123 更新时间:2023-12-02 08:59:49 26 4
gpt4 key购买 nike

我刚刚浏览了 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 并不总是读取要在套接字上读取的“所有内容”,并且有时只能返回其中的一部分。那么这样的话,这段代码岂不是错误的吗?我的意思是,在一次读取后,连接将被关闭......相反,我们不应该有其他一些机制吗?如果是这样,正确的方法是什么?

最佳答案

只有当recv()发生错误时,套接字才会被关闭,否则它将处理已读取的数据,即使它没有全部读取。当它再次循环时,它会读取更多内容。很确定这就是您要问的?

关于C:关于 Beej 的网络指南的问题......这里有一个假设吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2181339/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com