我已经创建了一个使用CocoaAsyncSocket的TCP套接字连接,并且每当我尝试执行didReadData时,我都会返回空格。当我设置断点并尝试调试时,我发现“msg”的值为@“”。使用CocoaAsyncSocket读取数据返回空格
这是我的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:插座didReadData:数据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:数据withTag:方法不被调用。任何帮助,将不胜感激。谢谢!
什么是DDLogError?你自己的日志功能? –
哦,不,它来自[Lumberjack](https://github.com/robbiehanson/CocoaLumberjack),一组有用的工具。 – vikingosegundo
我还没有彻底地通过StackOverflow的指导,但我认为最好不要在示例代码中使用第三方的东西。 NSLog()会保持简单,不太可能混淆新手。 –