在node.js上使用websockets加载聊天消息



嗨,我正在使用nodejs开发一个聊天应用程序,我是node的新手,所以我对它的功能不是很熟悉…我已经使我的应用程序存储在mysql数据库上的聊天消息,但我还需要显示过去的消息和当前的一个用户这里是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,你可以看到我提供的脚本。

几个建议:

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

2)使用socket。发送已存储的聊天消息,而不是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(); ?>

相关内容

  • 没有找到相关文章

最新更新