0
votes

I've been trying to do basic communication between an app and my server but no matter what I do I can't seem to get it to work. Below is my js code

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.on('connection', function(socket){
    console.log('a user connected');
    io.emit("hello");
    socket.on('disconnect', function() {
        console.log('a user disconnected');
    });
    socket.on('response', function(message){
        console.log(message);
    });
});


http.listen(3000, function(){
    console.log('listening on *:3000');
});

This should in theory be alerted when a user connects, output a message saying the user has connected and then emit an event "hello"

below the on disconnect part I am trying to communicate with the server from my iOS app. I emit a event called "response" with a string called "I got your response".

I get the "a user connected" message in the console but the message I send from the iOS app never gets printed in the console.

This the code in my app.

   override func viewDidLoad() {
       super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
       let socket = SocketIOClient(socketURL: "192.168.0.3:3000")
       socket.on("hello") {data, ack in
           socket.emit("response", "I got your response")
       }
       socket.connect()
   }

As you can see my server side code emits the event "hello". This should trigger the socket.on("hello") and make the app emit the event "response" which makes the server print out the string sent with it.

None of this is happening apart from the message that gets printed in the console when a user connects.

An help would be greatly appreciated.

the Github repo for the framework is below https://github.com/socketio/socket.io-client-swift

1
Check the logs for both server and client. For the client consider the option log:true (check the github repo for socket.io-client.swift) and for the server side run your node.js application as DEBUG=* node yourfile.js So you can have an idea which side is problematic. You can also use packet capture tool (e.g. wireshark) to see packets sent and received for further analysis. - cdagli
Have you tried making ur socket an instance variable. Its scoped to the function ur runnin it in now. A couple people had this issue - Greg Price
@GregPrice is right, if you enable logging you'l see that the socket only live in the score of this function, and get deallocated juste after. - user1585121

1 Answers

2
votes

Declare and initiate your socket variable in the top of the class. As previous comments said, I think the variable is lost in the scope otherwise.

class HostSocketHandler {
    let socket = SocketIOClient(socketURL: urlString)
    init(){
        socket.connect();
    }
}