当动态创建此字符串时(当我将其值设置为等于我的代码中的另一个变量之一时),我无法接收使用 UDP 数据包发送的字符串。不同的是,当我在创建这个字符串时为字符串设置了一个常量值时,这个问题不会出现。这是我用于发送字符串的方法:
- (void) sendUDPMessage {
int sockfd;
struct sockaddr_in server_addr;
char myBroad[]="255.255.255.255";
struct hostent *hptr = gethostbyname(myBroad);
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
bzero(&server_addr, sizeof(struct in_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(15000);
server_addr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
memcpy(&server_addr.sin_addr, hptr->h_addr_list[0], sizeof(struct in_addr));
int opt = 1;
setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &opt, sizeof(int));
NSString *string = [NSString stringWithFormat:@"%@ %@",user.name,user.surname];
sendto(sockfd, &string, sizeof(string), 0, (struct sockaddr*)&server_addr, sizeof server_addr);
NSLog(@"message sent : %@",string);
}
这是接收 udp 数据包的方法:
- (void) server {
int serverfd;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
serverfd = socket(AF_INET, SOCK_DGRAM, 0);
bzero(&server_addr, sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(15000);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(serverfd, (struct sockaddr *) &server_addr, sizeof(struct sockaddr_in));
socklen_t clisize = sizeof(struct sockaddr_in);
bzero(&client_addr, clisize);
while (1) {
NSString *string=@"";
NSLog(@"wainting for messages");
recvfrom(serverfd, &string, 200, 0, (struct sockaddr *) &sin, &clisize);
NSLog(@"message received : %@",string);
}
}
如果我定义 NSString * string = @"hello!"; 我可以正确接收字符串的内容。当我尝试发送 NSObject 时也存在同样的问题。我错过了什么?谢谢!