嗨,我是socket.io的新手,所以我不确定自己的操作是否是正确/标准的方法,但是由于运行良好,我想还不错。这个应用程序是聊天应用程序,我处理过的脚本能够将消息存储在数据库中并将其加载到接收者和发送者的浏览器中……问题是除非刷新页面,否则它不会加载到发送者的页面上奇怪的是,接收方在不刷新页面的情况下也能很好地接收数据,所以我就像“给出了什么?”
这是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);