【发布时间】:2012-05-13 20:51:12
【问题描述】:
目标:我正在制作一个 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;
}
【问题讨论】:
-
这看起来不像
C?! -
@Nick 说了什么。这些“@autoreleasepool”和“[NSString alloc]”是什么东西?猜测这个问题与字符串被 NULL 终止(或不终止)的方式有关,你可能会发现 buf 和 bufec 在内存中是相邻的,如果它们之间没有间隙,也没有空终止符,那么你就是一起打印出来。但是,如果没有更多信息,就无法分辨,例如什么是 BUFLEN?
标签: objective-c sockets udp