CocoaAsyncSockets creating Connection on app startup but Reading/Writing from a view(s)

247 views Asked by At

I am using the CocoaAsyncSockets library in order to create a tcp socket connection in my app. Currently, I have successfully created a connection by opening the socket connection in my didFinishLaunchingWithOptions method in my appDelegate.m file. My code looks like so:

- (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's my connect method:

- (void)connect 
{
    [socket connectToHost:@"9.5.3.6" onPort:11005 error:nil];
}

Now, what I have been struggling with is how to use read/write methods in my views without having to re-establish a connection.

  • I have established a tcp socket connection when the application launches
  • I open the socket in the didFinishLaunchWithOptions method so that I can create the connection and stay connected the entire time my app is running
  • I don't know how to read/write from/to the server from my views
  • I'm very new to socket/iOS development, so I'm hoping for the easiest possible solution

I would appreciate any help I can get on this. I'm still pretty new to iOS and still picking up on the syntax, so the more details anyone can provide, the better off I'll be.

Thanks so much for the help!

1

There are 1 answers

3
user523234 On BEST ANSWER

AsyncSocket comes with this method for writing:

- (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;

And several variants of read methods, here is one: (more from the header file of the library)

- (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag;

You should get the samples code from the same website that you have downloaded the AsyncSocket library to see how they are used. One thing to keep in mind is that these methods are asynchronous operations.