socket.io chat的例子 - sails.js

时间:2015-01-15 19:43:17

标签: javascript node.js socket.io sails.js

所以我尝试将socket.io集成到我的sails项目中。但是我在sails.js网站上找到了很少的文档。我试图在我的服务器的两个浏览器之间建立聊天。

在客户端我有:

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()`)
});

这是:/ posts / testStream:

testStream: function(req,res){

    res.view();
},

如何向客户端广播数据以及如何将messege发送回服务器?如果你能告诉我一个很棒的例子。

1 个答案:

答案 0 :(得分:7)

不知道,如果你需要它。以防万一,我自己的实践就是这样的例子。

我将CSS framework Semantic-UI用于样式,使用Knockout.js进行聊天渲染。此外,所有查询都由sails.io.js生成。在测试之前将它们放到 assets 文件夹中。

模型api / models / Chat.js:

module.exports = {

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

控制器api / controllers / ChatController.js:

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

查看观看次数/聊天/ 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>

只需打开http://yoursite/chat/do即可看到魔法=)