Sunday 28 May 2017

Cordova - SocketIO Not connecting

I am using cordova and socket.io to connect to my nodejs server

This is my server code

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

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

http.listen(port,function(){
    console.log("Listening to port ",port);
});

app.get('/', function(req, res){
  res.send('<h1>Hello world</h1>');
});

and this is my client code

app.initialize();

document.addEventListener('deviceready', function() {
    console.log("Device Ready!"); //displayed

    var socket = io('http://127.0.0.1:3000');
    //tried my LAN IP and still failed

    console.log('socket created'); //displayed
    console.log(typeof socket); // displays "object"

    socket.on('connect',function(){
        console.log("Connected!");
        //never displays
    });

    socket.on("message",function(data){
        console.log(data);
    });
});

I tried connecting to my nodejs server using this code hosted on my xampp/htdocs and it successfully connected!

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.1/socket.io.slim.js"></script>
</head>
<body>
    <script type="text/javascript">
        var socket = io('http://127.0.0.1:3000');

        socket.on('connect',function(){
            console.log("connected!");
        });

        socket.on('message',function(data){
            console.log(data);
        });

    </script>
</body>
</html>

I just don't understand why my cordova app won't trigger connect, perhaps it does not issue any error.

Any help is really appreciated.

Thank you!



via user1732887

No comments:

Post a Comment