Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of socket.io chat - sails.js

So I tried to integrate socket.io to my sails project. However I found very little documentation on the sails.js website. I'm trying to build a chat between two browser of my server.

in the client i have:

io.socket.get('/posts/testStream', function serverResponded (body, JWR) {

  // JWR ==> "JSON WebSocket Response"
  console.log('Sails responded with: ', body);
  console.log('with headers: ', JWR.headers);
  console.log('and with status code: ', JWR.statusCode);

  io.socket.on('messege', function onServerSentEvent (msg) {
      console.log(msg);
  });

  // first argument `body` === `JWR.body`
  // (just for convenience, and to maintain familiar usage, a la `JQuery.get()`)
});

and this is: /posts/testStream:

testStream: function(req,res){

    res.view();
},

How can i broadcast data to the client and how can i send messege back to the server? if you could show me with an example that would be great.

like image 804
Matan Gubkin Avatar asked Jan 15 '15 19:01

Matan Gubkin


1 Answers

Do not know, if you stil need it. Just in case and for my own practice here is working example.

I used CSS framework Semantic-UI for styles and Knockout.js for chat render. Also all queries are made by sails.io.js. Put them to assets folder before the test.

Model api/models/Chat.js:

module.exports = {

  attributes: {
      id: {
              type: 'integer',
              primaryKey: true,
              autoIncrement: true,
              unique: true
          },
      text: 'string'
  }
};

Controller api/controllers/ChatController.js:

module.exports = {
    do: function(req, res){
        return res.view();
    }
};

View views/chat/do.ejs:

<div class="ui very padded basic segment">
    <div class="ui feed" data-bind="foreach: { data: messages, as: 'message' }">
        <div class="event">
            <div class="content">
                <div class="summary">
                    Message ID <span data-bind="text: message.id"></span>
                    <div class="date" data-bind="text: message.createdAt"></div>
                </div>
                <div class="extra text" data-bind="text: message.text"></div>
            </div>
        </div>
    </div>
</div>
<div class="ui very padded basic segment">
    <form class="ui form" method="post" data-bind="submit: sendMessage">
        <label>Your message</label>
        <div class="ui field">
            <input type="text" name="message" value="" data-bind="value: newMessage"/>
        </div>
        <button class="ui primary button">Send</button>
    </form>
</div>
<script type="text/javascript">
var chatModel = function(){
    var self = this;
    this.messages = ko.observableArray();
    this.newMessage = ko.observable('');
    this.errors = ko.observableArray();

    /**
     * Send message to chat
     *
     * In fact, save to server and get show saved message in list
     */
    this.sendMessage = function(form){
        var self = this;
        if (self.newMessage().length > 0){
            io.socket.post('/chat', {text: self.newMessage()}, function(data, jwr){
                // If the message was created successfully, add it to messages array
                if (jwr.statusCode == 201){
                    self.messages.push(data);
                    self.newMessage('');
                } else {
                    self.errors.push('ERROR: ' + jwr.statusCode);
                }
            });
        }
    }.bind(this);

    /**
     * Get last 100 messages and connect to Chat websockets
     */
    io.socket.get('/chat', {sort: 'createdAt', limit: 100}, function(data, jwr){
        if (jwr.statusCode == 200){
            self.messages(data);
        } else {
            self.errors.push('ERROR: ' + jwr.statusCode);
        }
    });

    /*
        When a new message created by other user, add it to messages array
     */
    io.socket.on('chat', function(msg){
        if (msg.verb == 'created'){
            self.messages.push(msg.data);
        }
    });
};

ko.applyBindings(new chatModel());
</script>

Just open http://yoursite/chat/do and see the magic =)

like image 56
Bulkin Avatar answered Sep 17 '22 14:09

Bulkin