出于某种原因,当我尝试调用CocoaAsyncSocket的onSocket:didReadData:withTag方法时,它失败并且没有显示读取的数据。
的appDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSError *error = nil;
if (![socket connectToHost:@"199.5.83.63" onPort:11005 error:&error])
{
NSLog(@"Error connecting: %@", error);
}
[socket readDataWithTimeout:10 tag:1];
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.viewController = [[[tekMatrixViewController alloc] initWithNibName:@"tekMatrixViewController" bundle:nil] autorelease];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
以下是来自CocoaAsyncSocket Library的方法:
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length])];
NSString *msg = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
NSLog(@"RX length: %d", [data length]);
if(msg)
{
NSLog(@"RX:%@",msg);
}
else
{
NSLog(@"Fail");
}
}
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
NSLog(@"error - disconnecting");
//start reconnecting procedure here...
}
- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
NSLog(@"disconnected");
}
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
NSLog(@"connected");
}
当我在模拟器中运行我的应用程序时,这就是我的输出日志吐出的内容:
2012-06-08 13:17:30.808 tekMatrix[2793:f803] connected
2012-06-08 13:17:30.815 tekMatrix[2793:f803] RX length: 8
2012-06-08 13:17:30.816 tekMatrix[2793:f803] Fail
如果我错了,请纠正我,但它不应该“msg”包含从服务器读取的数据的值?看起来数据读取知道它期望数据长度为8,但数据似乎不会存储到字符串中。我是iOS的新手,尤其是socket编程,所以这对我来说都是新手。对此主题的任何帮助将不胜感激。
谢谢!
答案 0 :(得分:1)
我相信,服务器正在提供不是UTF-8编码的数据 请尝试
NSString *msg = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
并删除此行:NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length])];
如果这没有帮助,here are some more encodings尝试:
enum {
NSASCIIStringEncoding = 1,
NSNEXTSTEPStringEncoding = 2,
NSJapaneseEUCStringEncoding = 3,
NSUTF8StringEncoding = 4,
NSISOLatin1StringEncoding = 5,
NSSymbolStringEncoding = 6,
NSNonLossyASCIIStringEncoding = 7,
NSShiftJISStringEncoding = 8,
NSISOLatin2StringEncoding = 9,
NSUnicodeStringEncoding = 10,
NSWindowsCP1251StringEncoding = 11,
NSWindowsCP1252StringEncoding = 12,
NSWindowsCP1253StringEncoding = 13,
NSWindowsCP1254StringEncoding = 14,
NSWindowsCP1250StringEncoding = 15,
NSISO2022JPStringEncoding = 21,
NSMacOSRomanStringEncoding = 30,
NSUTF16StringEncoding = NSUnicodeStringEncoding,
NSUTF16BigEndianStringEncoding = 0x90000100,
NSUTF16LittleEndianStringEncoding = 0x94000100,
NSUTF32StringEncoding = 0x8c000100,
NSUTF32BigEndianStringEncoding = 0x98000100,
NSUTF32LittleEndianStringEncoding = 0x9c000100,
NSProprietaryStringEncoding = 65536
};
NSISOLatin1StringEncoding
也很常见。