【问题标题】:C TCP Echo Server - Data displays only on close()C TCP Echo 服务器 - 数据仅在 close() 时显示
【发布时间】:2013-08-30 15:39:52
【问题描述】:

所以,我在 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 客户端来发送数据,这是客户端的代码:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 7890))
s.send("hey server!")

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

【问题讨论】:

  • 您可能需要用fflush() 刷新stdout,因为io 已缓冲

标签: python c sockets tcp


【解决方案1】:

python 发送的示例有以下几种:

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

【讨论】:

  • 谢谢!问题是正是换行符。我在 C 代码中添加了一个“\n”,现在数据在发送时正确流动。再次,非常感谢。
【解决方案2】:

\n 起作用的原因是缓冲设置或默认为_IOLBUF。

请参阅函数setvbuf(),了解管理文件缓冲区(或 STDOUT)的不同方式。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 2015-01-18
    • 1970-01-01
    • 2021-04-25
    • 2020-12-11
    • 1970-01-01
    相关资源
    最近更新 更多