Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sailsjs SocketIO in iOS

I'm having a hard time wrapping my mind around a socket based chat app that I'm trying to do. I'm using sailsjs for my server side framework and trying to create a chat based app in iOS using SocketIO-Obj!

I have a successful handshake with the sailsjs framework, and the onConnect method in the sailsjs config/sockets.js file runs. but then after it's open how can I route to the controllers and actions I've created and still be able to access the request socket and subscribe them to my models

like image 729
fwhenin Avatar asked Feb 18 '26 03:02

fwhenin


1 Answers

Assuming you use the latest version of sails(0.10.0 and later), the protocol that sails uses on socket.io is not public, but you can read the source on the part how it's made, and how it is interpreted.

Basically it will emit an event, with the http verb as the event name and an object method, data, urls and headers. Something like this in Javascript:

var request = {
  data: data,
  url: url,
  headers: headers
};
socket.emit(method, request, callback);
  • method must be something like 'head', 'get', 'post' and etc.
  • data should be an object sending the request body. Optional.
  • url must be a string with no trailing slashes or spaces, like '/buy-a-cat' or '/cat/1/pat'.
  • headers should be an object, map of header names and values. Header names are lower-cased. Like { accept: '*/*' }. Optional.

I don't know much of objective-C and haven't tested this code, but you can do something like this, I think:

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:@"/cats" forKey:@"url"];

SocketIOCallback cb = ^(id argsData) {
    NSDictionary *response = argsData;
    // do something with response
};

[socketIO sendEvent:@"get" withData:dict andAcknowledge:cb];

Which in http request notation it would be equal to: GET /cats

Note that if you are using sails 0.9.x or lower the protocol is slightly different. Also do note that since sails isn't stable yet(not 1.x.x) this could change again, since this is not documented anywhere.

I have also found a project making sails http calls with SocketIO-Obj. It looks to be using 0.9.x protocol, but should be compatible with 1.x.x.

It looks like you can do this in it:

#import "SocketIO+SailsIO.h"


_socket = [[SocketIO alloc] initWithDelegate:self];
    [_socket connectToHost:@"localhost" onPort:1337];    

[_socket get:@"/user" withData:nil callback:^(id response) {
        NSLog(@"Records: %@", response);
}];
like image 80
Farid Nouri Neshat Avatar answered Feb 20 '26 16:02

Farid Nouri Neshat