出于某种原因,当我尝试调用 CocoaAsyncSocket 的 onSocket:didReadData:withTag 方法时,它失败并且不显示读取的数据。
应用委托:
- (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 库中的方法:
- (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
- onSocket:didConnectToHost:port 被调用,NSLog 吐出“已连接”。
- onSocket:didReadData:withTag 被调用,NSLog 吐出“RX length: 8”。
- 同样在 onSocket:didReadData:withTag 中,NSLog 吐出“失败”。
如果我错了,请纠正我,但它不应该“msg”包含从服务器读取的数据的值?看起来数据读取知道它期望数据长度为 8,但数据似乎没有存储到字符串中。我对 iOS 非常陌生,尤其是套接字编程,所以这对我来说是全新的。对此主题的任何帮助将不胜感激。
谢谢!