それで、私はCでTCPソケット接続に取り組んでいました.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 を実行しています。しかし、私はあることに気づきました。サーバーを使用して 1 つのデータのみを受信し、ループを削除すると、テキストがすぐに表示されます。シンプルな Python クライアントを使用してデータを送信しました。クライアントのコードは次のとおりです。
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 7890))
s.send("hey server!")
誰かが私を助けてくれることを願っています。