我正在尝试将数据发送到UDP服务器,我遇到了一些问题。发送后我没有收到数据。然后我尝试了一个网络记录器。我可以看到,当我使用NSUTF8Stringencoding
显示在网络日志上时,但当我使用NSASCIIEncoding
时,它不会发送。
我真的很想得到一些帮助。我正在使用CocaoAsyncUDPSocket
。如果任何人都无法再帮助接收数据,那真的很酷。
这是我的代码:
NSString *ipString = @"192.168.0.116:7777";
NSArray *splitArray = [ipString componentsSeparatedByString:@":"];
NSString *ip = [splitArray objectAtIndex:0];
NSString *port = [splitArray objectAtIndex:1];
NSArray *ipArray = [ip componentsSeparatedByString:@"."];
char ipNumber1 = [self chr:[[ipArray objectAtIndex:0] intValue]];
char ipNumber2 = [self chr:[[ipArray objectAtIndex:1] intValue]];
char ipNumber3 = [self chr:[[ipArray objectAtIndex:2] intValue]];
char ipNumber4 = [self chr:[[ipArray objectAtIndex:3] intValue]];
char portByte1 = [self chr:[port intValue] & 0xFF];
char portByte2 = [self chr:[port intValue] >> 8 & 0xFF];
NSString *packetString = [NSString stringWithFormat:@"SAMP%c%c%c%c%c%cp4150", ipNumber1, ipNumber2, ipNumber3, ipNumber4, portByte1, portByte2];
GCDAsyncUdpSocket *socket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *err = nil;
NSData *data = [packetString dataUsingEncoding:NSASCIIStringEncoding];
[socket sendData:data toHost:ip port:[port intValue] withTimeout:-1 tag:1];
NSLog(@"%@", packetString);
这个永远不会被称为:
-(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext; {
NSLog(@"Received data");
}
编写的相同功能
答案 0 :(得分:0)
NSString
用于一系列Unicode字符,不能用作容器
你在这里的任意字节序列。
您最好先在字节缓冲区中构建消息,然后将其直接转换为
NSData
:
unsigned char buffer[20]; // Choose a size that is large enough for your messages
memcpy(&buffer[0], "SAMP", 4);
buffer[4] = [[ipArray objectAtIndex:0] intValue];
buffer[5] = [[ipArray objectAtIndex:1] intValue];
buffer[6] = [[ipArray objectAtIndex:2] intValue];
buffer[7] = [[ipArray objectAtIndex:3] intValue];
buffer[8] = [port intValue] & 0xFF;
buffer[9] = [port intValue] >> 8 & 0xFF;
memcpy(&buffer[10], "p4150", 5);
int messageSize = 15;
NSData *data = [NSData dataWithBytes:buffer length:messageSize];