我已經創建了一個使用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()會保持簡單,不太可能混淆新手。 –