Integrate cross-domain-socket.io using sails.io li

2019-09-06 05:06发布

I have written a chat application based on sails.js on my server so basiclly all the code in the client side was running on the localhost.

the chat is working like a dream but now i want to move all the client side to my cordova application.

this is my server side code(socket.js)

onConnect: function(session, socket) {

    // By default, do nothing.
    console.log('hello');
    socket.emit('news', "Welcome to the chat");

    socket.on('send message', function(data){
        console.log(data);
        socket.broadcast.emit('new', data);
        sails.sockets.emit(sails.sockets.id(socket),'new', data);
    });
},

this is my client side(server localhost) chat file:

$('#form1').submit(function(e){
    e.preventDefault();
    io.socket.emit('send message', $('#userText').val());
    $('#userText').val('');
});

io.socket.on('news', function (msg) {
    console.log(msg);
    $('#content').append(msg + '<br />');
});

io.socket.on('new', function(data){
    console.log(data);
    $('#content').append(data + '<br />');
});

and this is client side(server localhost) that request the userCategories API:

io.socket.get('http://178.62.83.248:1337/userCategories', function (resData)    {
   console.log(resData); // => {id:9, name: 'Timmy Mendez'}
});

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

now here is what i tried on my cordova client(index.js):

<script src="lib/sails.io.js/sails.io.js"></script>
<script>
    io.sails.url = 'http://178.62.83.248:1337';
    io.socket.get('http://178.62.83.248:1337/userCategories', function (resData) {
      console.log(resData); // => {id:9, name: 'Timmy Mendez'}
    });

    io.socket.on('usercategories', function(message){
        console.log(message);
    });
</script>

this code acts in a very weird way.when the application starts, it tries to connect to: http://178.62.83.248:1337/__getcookie and then it fails? and returns me this message in the console:

        Socket is trying to reconnect to Sails...
 _-|>_-  (attempt #1)

        Socket is trying to reconnect to Sails...
 _-|>_-  (attempt #2)

attempt 43, 44, etc...

so I hope someone can explain me what is this mean and how can I fix this.

1条回答
地球回转人心会变
2楼-- · 2019-09-06 05:14

I have solved this problem. The reason this is happening is because when you install sails.io file on your client you actually installing the newest version. In order to connect to your server you need to use the right version of sails io.js. In my case I used sails 10.5 on the server so I had to include the specific file in my client

查看更多
登录 后发表回答