我使用 CocoaAsyncSocket 创建了一个 TCP 套接字连接,每当我尝试执行 didReadData 时,我都会返回空白。当我设置断点并尝试调试时,我发现“msg”的值是@“”。
这就是我的 appDelegate.m 的样子:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSData *data = nil;
// Initialize socket object and make it a delegate. Then call the delegate methods.
socket = [[AsyncSocket alloc] initWithDelegate:self];
[self connect];
[self onSocket:socket didConnectToHost:@"9.5.8.6" port:11005];
[self onSocket:socket didReadData:data withTag:1]; // tags COULD be #defined *******
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;
}
这是我的 onSocket:socket didReadData:data withTag: 方法:
- (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];
if(msg)
{
NSLog(@"RX:%@",msg);
if(msg == nil)
{
NSLog(@"msg is all Blanks");
}
}
else
{
NSLog(@"Fail");
}
}
请注意,此方法是来自 CocoaAsyncLibrary 的方法。我不知道我是否正确调用了该方法,或者我是否没有传递正确的参数,或者什么。
当我运行该应用程序时,我在控制台中看到的只是:
2012-06-06 11:44:00.434 tekMatrix[1378:f803] connected
2012-06-06 11:45:14.312 tekMatrix[1378:f803] RX:
非常感谢任何和所有帮助。
谢谢!
编辑
这是我现在的 didFinishLaunchingWithOptions 方法中的内容:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
socket = [[AsyncSocket alloc] initWithDelegate:self];
NSError *error = nil;
if (![socket connectToHost:@"199.5.83.63" onPort:11005 error:&error])
{
NSLog(@"Error connecting: %@", error);
}
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;
}
现在我可以看到我已连接,但我仍然不理解 onSocket:socket didReadData:data withTag: 方法未被调用。对此的任何帮助将不胜感激。谢谢!