Socket.io 从接收者的浏览器发出,但不在发送者的浏览器上发出



嗨,我对socket有点陌生。所以我不确定我所做的是否正确/标准的方式,但因为它运行良好,我想它很好。这个应用程序是聊天应用程序的脚本,我工作的是能够在数据库上存储消息,并将它们加载到接收方和发送方的浏览器…问题是它不加载在发送者的页面上,除非我刷新页面,我发现这很奇怪,因为接收方收到的数据很好,没有刷新页面,所以我就像"什么给?"

这里是server.js
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 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());
    $('#m').val('');
    return false;
  });
  socket.on('chat message', function(msg){
    $('#messages').append($('<li class="bubble">').text(msg));
  });

    </script>

  <?php endblock(); ?>

有任何建议或我错过了什么??我尝试将socket.broadcast.emit('chat message', msg);更改为socket.emit('chat message', msg);,但它不起作用,它确实在发送者的浏览器上加载,但在接收者上没有,请帮助我

:)

用下面这行在客户端本地添加消息:

$('#messages').append($('li').text($('#m').val()));

或替换以下内容:

socket.broadcast.emit('chat message', msg);
与这个:

io.sockets.emit('chat message', msg);

相关内容

  • 没有找到相关文章

最新更新