目標: データを送受信するための UDP ソケットを作成しています。私はラップトップでこれをテストしているので、受信メッセージをリッスンしてこれをエコーバックするサーバーをバックグラウンドで実行しています。
問題: サーバーが 1 つの文字列を受信し、それがエコー バックすると、クライアントは文字列を 1 回ではなく 2 回読み取り、意味不明な文字列を追加します。これを解決するにはどうすればよいですか?
コードからの出力は次のとおりです。
コード:
#define BUFLEN 5
#define PORT 12345
#import <Foundation/Foundation.h>
#define srvr_IP "127.0.0.1"
void errorSig(char *);
int main (int argc, const char * argv[])
{
int sockSend = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in si_other;
char buf[BUFLEN] = "Hello";
char bufrec[BUFLEN];
@autoreleasepool {
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);
inet_pton(AF_INET, srvr_IP, &si_other.sin_addr);
memset(&si_other.sin_zero, 0, sizeof(si_other.sin_zero));
int size = sizeof(si_other);
sendto(sockSend, buf, BUFLEN, 0,
(struct sockaddr *)&si_other, size);
recvfrom(sockSend, bufrec, BUFLEN, 0, (struct sockaddr *)&si_other, (unsigned int*)&size);
NSString *test = [[NSString alloc]initWithUTF8String:bufrec];
NSLog(@" data is: %@", test);
close(sockSend);
}
return 0;
}