C TCP Echo服务器数据仅在close()时显示

2024-09-28 22:19:22 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我在C语言中开发了一个TCP套接字连接。我制作了一个echo服务器,它使用getaddrinfo(),然后bind(),listen(),accept,最后启动while循环来接收数据,直到客户端断开连接。在

问题是:代码显然可以工作,但是在循环中接收到的数据只在客户端断开连接时显示。我希望发送到服务器的数据在客户端连接时显示出来,就像一个简单的聊天。数据被发送,服务器会立即看到它。在

代码如下:

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>

int main(void) {

    struct sockaddr_storage their_addr;
    socklen_t addr_size;
    struct addrinfo hints, *res;
    int sockfd, newfd;

    int numbytes;
    char buf[512];

    // first, load up address structs with getaddrinfo():

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;  // use IPv4 or IPv6, whichever
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;     // fill in my IP for me

    getaddrinfo(NULL, "7890", &hints, &res);

    // make a socket, bind it, and listen on it:

    sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    bind(sockfd, res->ai_addr, res->ai_addrlen);
    listen(sockfd, 1);

    // now accept an incoming connection:

    addr_size = sizeof(their_addr);
    newfd = accept(sockfd, (struct sockaddr *)&their_addr, &addr_size);

    while((numbytes = recv(newfd, buf, sizeof(buf), 0)) > 0) {

        buf[numbytes] = '\0'; // sets the character after the last as '\0', avoiding dump bytes.
        printf("%s", buf);

    }

    return 0;
}

如果这有什么关系的话,我运行的是Linux。然而,我注意到了一些事情。如果我删除循环,使用服务器只接收一条数据,文本将立即显示。我使用了一个简单的Python客户端来发送数据,以下是客户端的代码:

^{pr2}$

希望有人能帮助我,提前感谢任何尝试过的人!在


Tags: 数据代码服务器客户端includebindreslisten
2条回答

\n有效的原因是缓冲区已设定或预设为\u IOLBUF。在

有关管理文件(或STDOUT)缓冲区的不同方式的说明,请参阅函数setvbuf()。在

最后,需要注意的是,如果发出fflush(stdout);,这将强制刷新缓冲区,并且与文件的缓冲标志值无关。在

python send的示例有以下几种:

def mysend(self, msg):
    totalsent = 0
    while totalsent < MSGLEN:
        sent = self.sock.send(msg[totalsent:])
        if sent == 0:
            raise RuntimeError("socket connection broken")
        totalsent = totalsent + sent

原因是在关闭套接字或遇到新行之前,数据可能不会被发送。有关详细信息,请参见Python Socket Programming HOW-TO

相关问题 更多 >