drekka
drekka

Reputation: 21883

Node.js socket.io not responding to iOS socket.io emit requests

I can't seem to figure this one out. I'm testing the usage of socket.io to connect an iOS client app with a Node.js server. My server code looks like this:

var io = SocketIO(8099, { log: true });

io.on('connection', function (socket) {

    socket.on('connect', function (data) {
            console.log('Connected, data: ' + data);
        });

    socket.on('getProjects', function(from, msg) {
        database.allProjects(function getAllProjectsCallback(err, rows) {
            console.log('Got the project list');
            socket.emit('projectList', rows);
        });
    });

});

My iOS code starts with:

_socket = [[SocketIOClient alloc] initWithSocketURL:@"http://localhost:8099" opts:nil];

    [_socket on:@"connect" callback:^(NSArray* data, SocketAckEmitter* ack) {
        NSLog(@"socket connected");
    }];

    [_socket on:@"projectList" callback:^(NSArray* data, SocketAckEmitter* ack) {
        NSLog(@"Project list received");
        [ack with:@[]];
    }];

    [_socket connect];

And in another method I have this code which should send the get projects request:

[_socket emit:@"getProjects" withItems:@[]];

I can see the iOS "socket connected" message in the log. But not the Node.js "Connected, ..." message. When I trigger the [_socket emit:@"getProjects" ...] in iOS, nothing happens on the server. Neither the 'connect' or 'getProjects' events are called.

I've trolled the internet and as far as I can tell, I've done everything as per all the blogs and examples I can find.

What am I missing in this setup? Or have I fundamentally miss-understood something?

Upvotes: 1

Views: 1504

Answers (2)

drekka
drekka

Reputation: 21883

Just realised this was all my bad. I had the timing wrong because I was refactoring from code that worked with a different comms model. My code was managing to execute the emit after the socket had been created but before it was ready to send data.

Everything working now. Thanks.

Upvotes: 1

bookotl
bookotl

Reputation: 68

I have no knowledge about iOS code. But I saw something wrong in your server code.

 socket.on('connect', function (data) {
        console.log('Connected, data: ' + data);
 });

Above code mean when someone send data to socket name "connect" its will console.log that data.

I think this is what your code should look like.

var io = SocketIO(8099, { log: true });

io.on('connection', function(socket) {
    console.log('New Connection');
    socket.on('getProjects', function(data) {
        database.allProjects(function getAllProjectsCallback(err,  rows) {
            console.log('Got the project list');
            socket.emit('projectList', rows);
        });
    });
});

Upvotes: 0

Related Questions