【发布时间】: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 已缓冲