0

目标:我正在制作一个 UDP 套接字来发送和接收数据。我正在我的笔记本电脑上对此进行测试,所以我有一个在后台运行的服务器,它监听传入的消息并将其回显。

问题:我看到服务器收到一个字符串,当它回显时,客户端读取字符串 2 次而不是 ONE 并添加乱码。如何解决这个问题?

代码的输出是:HelloHello09[顺便说一句,我在 09 前面和后面都有一些倒置的问号,但我不能粘贴它,lolz]

代码:

#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;
}
4

1 回答 1

1

我刚刚看到您实际上确实将 BUFLEN 定义为 5(抱歉,当我在上面写我的评论时我错过了)。正如我所怀疑的,您有一个 NULL 终止问题。C 中字符串的长度比您要存储的字符数多一,以便为指示字符串结尾的 NULL 终止符腾出空间。

将您的 BUFLEN 定义更改为 6,您应该会发现它工作得更好。

于 2012-05-04T10:16:29.973 回答