我遇到了麻煩,它接收到我用UDP數據包發送的字符串,當這個字符串是動態創建的(當我設置其值等於另一個變量在我的代碼中)。這個問題並沒有出現,當我創建一個不同的字符串時,我給它設置了一個常量值。 這裏是我用來發送字符串的方法:Objective-c插座 - 無法正確接收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 *[email protected]"";
NSLog(@"wainting for messages");
recvfrom(serverfd, &string, 200, 0, (struct sockaddr *) &sin, &clisize);
NSLog(@"message received : %@",string);
}
}
如果我定義的NSString *字符串= @「你好!」;我可以正確接收字符串的內容。當我嘗試發送一個NSObject時也存在同樣的問題。 我錯過了什麼?謝謝!
這確實是一個初始的劃痕,所有需要的檢查都將在基本操作正常工作時執行!謝謝您的幫助! – whiplash