私は現在、サーバーとクライアントの間でメッセージを渡す際に問題が発生しています。 私が知る限り、 Beejのソケットプログラミングチュートリアルで概説されているソケットプログラミングのベストプラクティスを正しく実行しています。
2つのプロセスを実行すると、受信したバイト数ではなく、recv()システムコールが-1(エラー)を返します。また、bufを出力しようとするときに、ゴブリンの文字がたくさんあります。どちらが理にかなっているのは、エラーのためです。
私はrecv()で問題が発生している理由について誰かが正しい方向に向けることができるかどうか疑問に思っていますか?関連するコードスニペットは次のとおりです。
サーバ:
struct sockaddr_storage their_addr;
socklen_t addr_size;
int sockfd, newfd, byte_count, status;
char buf[512];
struct addrinfo hints, *res;
// first, load up address structs with getaddrinfo():
memset(&hints, 0, sizeof hints);
hints.ai_family = PF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// get address info, print stuff if error
if((status = getaddrinfo("nunki.usc.edu", "21957", &hints, &res)) !=0){
fprintf(stderr, "getaddrinfo error: %sn", gai_strerror(status));
exit(1);
}
// make a socket:
if((sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1){
cout << "socket fail" << endl;
}
// bind the socket to the port
bind(sockfd, res->ai_addr, res->ai_addrlen);
// required output
cout << "Phase1: Login server has TCP port number " << "21957 "
<< "and IP address " << getIPfromHost("nunki.usc.edu") << endl;
// listen for incoming connections
listen(sockfd, 10);
cout << "after listen" << endl;
// halt until receipt
addr_size = sizeof(their_addr);
newfd = accept(sockfd, (struct sockaddr *)&their_addr, &addr_size);
cout << "after accept" << endl;
// Now that we're connected, we can receive some data
byte_count = recv(sockfd, buf, sizeof buf, 0);
printf("recv()'d %d bytes of data in bufn", byte_count);
printf("Msg is %sn", buf);
クライアント:
struct addrinfo hints, *res;
int sockfd;
// first, load up address structs with getaddrinfo():
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
getaddrinfo("nunki.usc.edu", "21957", &hints, &res);
// make a socket:
if((sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1){
cout << "socket fail" << endl;
}
// attempt connection to port
if(connect(sockfd, res->ai_addr, res->ai_addrlen) == -1){
cout << "connect fail" << endl;
}
// send message to server
cout << "sockfd " << sockfd << endl;
int byte_count = send(sockfd, "Hello", 5, 0);
cout << byte_count << endl;
The following is the output for サーバ:
Phase1: Login server has TCP port number 21957 and IP address 68.181.201.3
after listen
after accept
recv()'d -1 bytes of data in buf
Msg is ÿhÿ?sÈ
Glæ
The following is the output for クライアント:
sockfd 4
5
ベストアンサー
間違ったソケットで recv
を呼び出しています。 newfd
に
recv
する必要があります。
byte_count = recv(newfd, buf, sizeof buf, 0); /* newfd instead of sockfd. */
今はそれが途方もない、
私が知る限り、私は適切にソケットのベストプラクティスに従っています プログラミング
私は完全に同意しない。
- プログラムに
strerror
やperror
はありません
listen
、 bind
、getaddrinfo
などのリターンステータスを確認していません。