问题
I have created a TCP Socket connection in my appDelegate didFinishLaunchingWithOptions
method. That was the easy part, and I have successfully connected to my server. I am having great difficulty with reading the data from the server in my View. I have been looking through tutorials on how to appropriately (step by step) read data using CocoaAsyncSocket, but I haven't come across anything useful.
This is my code from my appDelegate:
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
socket = [[AsyncSocket alloc] initWithDelegate:self];
[self connect];
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;
}
And here is my connect method, at the bottom of the appDelegate file:
- (void)connect
{
[socket connectToHost:@"9.5.3.3" onPort:11005 error:nil];
}
That was the easy part. I now need to read data from the server. I know some kind of NSData or NSMutableData object needs to be created for to take the value of the data I read from the server. I just have been very unsuccessful in finding any tutorial or documentation that points me in the right direction. There are several different read functions, some with different parameters, etc. If anyone could point me to a resource that goes over this in depth*(I am a newbie, after all =P)* I would really appreciate it -- Or if somebody knows of an easy way to accomplish this goal and wouldn't mind providing sample code here :D
This is the library I'm using: CocoaAsyncSocket. I'm using the library AsyncSocket.h
and AsyncSocket.m
I've been stuck at this for hours, so any help would be great appreciated.
Thanks!
回答1:
This should work:
- (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);
}
}
You should also implement some other delegate methods, for example:
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
NSLog(@"error - disconnecting");
//you'd probably want to start reconnecting procedure here...
}
- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
NSLog(@"disconnected");
}
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
NSLog(@"connected");
}
EDIT: if memory serves me right there is some documentation and also some examples available with the library.
来源:https://stackoverflow.com/questions/10902710/how-do-i-read-data-using-cocoaasyncsocket