2014-02-08 163 views
0

我試圖將數據發送到UDP服務器,並且出現了一些問題。發送後我沒有收到數據。然後我嘗試了一個網絡記錄器。我可以看到當我使用NSUTF8Stringencoding它顯示在網絡日誌上,但是當我使用NSASCIIEncoding時,它不會發送。通過套接字發送數據時的編碼問題

我真的很喜歡一些幫助。我正在使用CocaoAsyncUDPSocket。如果anynone可以幫助再次獲得數據,那將非常酷。

這裏是我的代碼:

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"); 
} 

下面是用C#編寫相同的功能http://wiki.sa-mp.com/wiki/Query_Mechanism/Csharp

回答

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]; 
+0

非常感謝該代碼的工作!你有可能解釋代碼,所以我可以從中學習嗎? – user3287428

+0

@ user3287428:哪部分你不明白? –

+0

沒關係。我現在明白了。儘管我可以在閱讀返回的字節時使用一些幫助。我如何讀取字節?下面是字節的排列方式:http://wiki.sa-mp.com/wiki/Query_Mechanism#Response_from_i i的一個響應 – user3287428

相關問題