0

Hello I'm trying to use the following cocoa pod for tcp functionality in ios: https://cocoapods.org/pods/CocoaAsyncSocket

Im facing problems writing the marshalled js using this library

Here is an example (Objective C):

// The most common way to initialize an instance is simply like this:
socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

NSError *err = nil;
if (![socket connectToHost:@"deusty.com" onPort:80 error:&err]) // Asynchronous!
{
    // If there was an error, it's likely something like "already connected" or "no delegate set"
    NSLog(@"I goofed: %@", err);
}
- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"Cool, I'm connected! That was easy.");
} 

JSCODE:

// mainQueue var is to get dispatch_get_main_queue
var mainQueue = (function() {
    var runloop = CFRunLoopGetMain();
    return function(func) {
        CFRunLoopPerformBlock(runloop, kCFRunLoopDefaultMode, func);
        CFRunLoopWakeUp(runloop);
    }
}());

var tcpClient = GCDAsyncSocket.alloc().initWithDelegateDelegateQueue(testerClass,mainQueue);
var e = new interop.Reference();
if (!tcpClient.connectToHostOnPortError('192.168.88.110',3333,e)) {
    console.log('Could not connect to mipbook');
    console.log(e.value);
}
function socketDidConnectToHost(sock,host,port) {
    console.log('connected to host');
}

The connect to port part is working fine, but the delegate instance method is not being called when the connection is successful.

Samy Brom
  • 3
  • 3

2 Answers2

0

Ok, I got it to work The problem was with marshalling dispatch_get_main_queue(). I got my script to work by editing GDCAsyncSocket.m in the source of the pod used.

GDCAsyncSocket.m:

delegateQueue = dq;

change to

delegateQueue = dispatch_get_main_queue();

this way dispatch_get_main_queue() is no longer needed to be passed from the js side, its value is evaluated in the objective c library.

Here is the working JS code:

var tcpClientDelegate = NSObject.extend({
    socketDidConnectToHostPort(sock,host,port) {
        console.log('connected to host: '+host);
        console.log('connected to port: '+port);
    }
}, {
    protocols: [GCDAsyncSocketDelegate]
});

var clientInstance = new tcpClientDelegate();
var tcpClient = GCDAsyncSocket.alloc().initWithDelegateDelegateQueue(clientInstance,null);
var e = new interop.Reference();
if (!tcpClient.connectToHostOnPortError('192.168.88.110',3333,e)) {
    console.log('Could not connect to mipbook');
    console.log(e.value);
}
Samy Brom
  • 3
  • 3
0

Tried with this:

let delegate = ...
let dispatchQueue = dispatch_queue_create("test_queue", null);
let udp = GCDAsyncSocket.alloc().initWithDelegateDelegateQueue(delegate, dispatchQueue);

And it works fine. Should also work for GCDAsyncSocket. For some reason dispatch_get_main_queue() is undefined.