0

I'm trying to write a simple client that should connect to a server with TCP using CocoaAsyncSocket. I have a class, MyClass that is set as the delegate to CocoaAsyncSocket and when building a "Cococa Application" (with UI) this class works as it should and connects to the server and the didConnectToHost method is being called.

Working

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    self.my = [[MyClass alloc] init];

    [self.my connect];

}

However, when building a console application with the main file below, it doesn't work. I just want to fire off this class and let it run in the background.

Not working

#import <Foundation/Foundation.h>
#import "MyClass.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        NSLog(@"Hello, World!");

        MyClass * my = [[MyClass alloc] init];

        [my connect];

        while(1) {
            NSLog(@"Nothing");
            sleep(1);
        }
    }
    return 0;
}
norq
  • 1,404
  • 2
  • 18
  • 35

1 Answers1

3

This will not work because CocoaAsyncSocket relies on the NSRunLoop to be running, instead your sleep(1) is constantly running on the main thread. Perhaps replace your infinite while loop for:

[[NSRunLoop mainRunLoop] run];
kylef
  • 1,066
  • 1
  • 8
  • 11