【问题标题】:Load chat messages upon page load using websockets on node.js在 node.js 上使用 websockets 在页面加载时加载聊天消息
【发布时间】:2014-09-26 12:01:24
【问题描述】:

您好,我正在使用 nodejs 开发一个聊天应用程序还显示过去的消息,当前用户是 index.js

    var mysql =  require('mysql'); 
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var validator;

var connection =  mysql.createConnection({ // setup the connection
        host : "localhost",
        user : "root",
        password: "",
})
function getStdout(command, args, fn) {
    var childProcess = require('child_process').spawn(command, args);
    var output = '';
    childProcess.stdout.setEncoding('utf8');
    childProcess.stdout.on('data', function(data) {
        output += data;
    });
    childProcess.on('close', function() {
        fn(output);
    });
}

app.use('/assets', require('express').static(__dirname + '/assets'));
app.use('/temp', require('express').static(__dirname + '/temp'));
app.get('/', function(req, res){
  //res.sendfile(__dirname + '/' +validator);
  res.send(validator);
});

//you should have only one io.on('connection')
io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    console.log('message: ' + msg);

       var myMsg= msg; // obtain the incoming msg
  var strQuery = "INSERT INTO chat_storage(chat) VALUES(?)"; // your SQL string

  connection.query("use schat"); // select the db
  connection.query( strQuery, myMsg, function(err, rows){
     if(err) {
        // handle errors
     } else {  
      io.emit('chat message', msg);
        // message received
     }
   }); 

  });
});

getStdout('php', ['message.php'], function(output) {
  validator = output;
  //start your server after you get an output
  http.listen(3000, function(){
    console.log(validator);
  });
});

现在是加载聊天消息的页面

    <?php startblock('script') ?>

 <script src="/socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      $(document).ready(function(){

      $.ajax({ 
        url: "localhost:3000/includes/message/store_chat.php",
        type: "POST",
          dataType: "html",
        success: function (result) {
          $("#messages").html(result);

        }
      });

      });

      var socket = io();
      $('form').submit(function(){
        socket.emit('chat message', $('#m').val());
        $('#m').val('');
        return false;
      });
      socket.on('chat message', function(msg){

         $('#messages').append($('<li>').text(msg));
});
</script>
<?php endblock(); ?>

我的想法是页面加载后的聊天消息,我试图使用 ajax 来实现它,正如你在我提供的脚本上看到的那样。但它根本不起作用请帮助我

【问题讨论】:

    标签: ajax node.js websocket socket.io


    【解决方案1】:

    几个建议:

    1) 将所有消息存储在内存中(除非您看到它增长到数 MB 的数据),以便您可以快速赶上任何新客户。

    2) 使用 socket.io 发送已存储的聊天消息,而不是 AJAX 调用。

    我还包含了 SequelizeJS 而不是原始 MySQL - 它具有更清晰的原始查询模型,并且允许您根据需要转换为各种 DAO 模型。

    app.js

    // Highly suggest replacing raw mysql with SequelizeJS - http://sequelizejs.com/
    var Sequelize = require('sequelize'),
      app = require('express')(),
      http = require('http').Server(app),
      io = require('socket.io')(http);
    
    var validator;
    var messages = [];
    
    var sequelize = new Sequelize('schat', 'root', '');
    
    app.use('/assets', require('express').static(__dirname + '/assets'));
    app.use('/temp', require('express').static(__dirname + '/temp'));
    app.get('/', function(req, res){
      res.send(validator);
    });
    
    io.on('connection', function(socket){
      // Send all previously sent messages
      for( i in messages ) {
        socket.emit('chat message', messages[i]);
      }
    
      socket.on('chat message', function(msg){
        console.log('message: ' + msg);
    
        // Push the message into the in-memory array.
        messages.push(msg);
    
        // Storage the message for when the application is restarted.
        sequelize.query('INSERT INTO chat_storage(chat) VALUES("'+msg'")').success(function() {
          // Insert was successful.
        }).error(function (err) {
          // Error inserting message
        });
    
        // Send the message to everyone
        socket.broadcast.emit('chat message', msg);
      });
    });
    
    function getStdout(command, args, fn) {
      var childProcess = require('child_process').spawn(command, args);
      var output = '';
      childProcess.stdout.setEncoding('utf8');
      childProcess.stdout.on('data', function(data) {
        output += data;
      });
      childProcess.on('close', function() {
        fn(output);
      });
    }
    
    // Load Messages
    sequelize.query('SELECT chat FROM chat_storage').success(function (rows) {
      for( i in rows ) {
        messages.push(rows[i].chat);
      }
      getStdout('php', ['message.php'], function(output) {
        validator = output;
        http.listen(3000, function(){
          // Start server.
        });
      });
    }).error(function (err) {
      // Error!
    });
    

    php 包含

    <?php startblock('script') ?>
    
    <script src="/socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      var socket = io();
      $('form').submit(function(){
        socket.emit('chat message', $('#m').val());
        $('#messages').append($('li').text($('#m').val()));
        $('#m').val('');
        return false;
      });
      socket.on('chat message', function(msg){
        $('#messages').append($('<li>').text(msg));
      });
    </script>
    <?php endblock(); ?>
    

    【讨论】:

    • 这就像魅力一样,因此可以在没有 ajax 的情况下做到这一点,尽管 DAO 是什么?抱歉,我还在学习,网络开发还有很长的路要走
    • DAO = 数据访问对象 (en.wikipedia.org/wiki/Data_access_object)。这个想法基本上是使用 Javascript 对象来表示数据库中的行;因此,与其编写一些冗长的 SQL 查询,不如做一些类似 var obj = new MyObject(); 之类的事情。 obj.name = "随便"; obj.save();你可以在这里找到更多信息:sequelizejs.com/docs/1.7.8/models
    • 我看到的唯一问题是,除非我刷新页面,否则它不会在按下回车键或单击发送按钮时显示消息..
    • 上面的代码不会将消息发送回发送消息的客户端 - 我已经使用以下行对其进行了编辑:$('#messages').append($( 'li').text($('#m').val()));
    • 很抱歉,它确实从接收方加载了邮件,但从发件人一方,除非刷新,否则它不会显示...
    猜你喜欢
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多