Integrate cross-domain-socket.io using sails.io library to client

故事扮演 提交于 2019-12-12 03:23:47

问题


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:


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



来源:https://stackoverflow.com/questions/28141969/integrate-cross-domain-socket-io-using-sails-io-library-to-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!