简体   繁体   中英

Connect to Sails WebSocket

I'm triying to develop a simple Hello World Websocket using Sails framework V0.12. I need to connect an external Basic Front-End (HTML,CSS,JS) to that Sails WebSocket server. Send a simple event and retrieving 'Hello World!!' I'm using Sails API sails.io.js.

I have tried this in Front-End

<!doctype html>
<html>

<head>
    <script type="text/javascript" src="js/dependencies/sails.io.js"></script>
    <script type="text/javascript">
    window.onload = function() {
        io.sails.url = 'http://localhost:1337';

        io.socket.get('http://localhost:1337/helloworld', function(body, sailsResponseObject) {
            console.log('Sails responded with: ', body);
            console.log('with headers: ', sailsResponseObject.headers);
            console.log('and with status code: ', sailsResponseObject.statusCode);
        });


    };
    </script>
</head>

<body>
    <ul id='messages'></ul>
    <button onclick="pagar()">Click me</button>
</body>

</html>

I know that is connecting to Sails, but I I'm not able to get WebSocket response. Sails response is 404 (Not found). How can i create that WebSocket Using Sails Socket. Thanks a lot!

you can try this, working on sails 0.12

views/user/*.ejs

<div id='messages'></div>
<button id="pagar">Click me</button>
<script>
$('#pagar').click(function(){     
io.socket.post('/user/message', {message: 'hi world'});

});

</script>

api/controllers/UserController.js

  module.exports = {
      message: function(req, res) { 

            var io = sails.io;
            // emit to all sockets            
            io.sockets.emit('code', {message: req.param('message')});

        }
    }

//Front-End js assets/js/app.js

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


    io.socket.on('code', function (data) {

         $("#messages").text(data.message);
        console.log('Sails responded: ', data.message);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM