嗨,我对socket.io有点新意,所以不确定我所做的是正确的/标准的方式,但由于它的运行良好,我猜它很好。这个应用程序是聊天应用程序,我工作的脚本能够在数据库上存储消息并将它们加载到接收方和发送方的浏览器......问题是它不会加载到发送方的页面,除非我刷新页面更多我发现它很奇怪,因为接收器接收数据就好了而没有刷新页面所以我就像#34;什么给出了?"
这是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);
,但它无效,它会在发件人的浏览器上加载,但不会在收件人上请帮助我
答案 0 :(得分:1)
:)
使用以下行在客户端本地添加消息:
$('#messages').append($('li').text($('#m').val()));
或替换以下内容:
socket.broadcast.emit('chat message', msg);
有了这个:
io.sockets.emit('chat message', msg);