[英]Socket.io Client Not Receiving Data from Server Correctly
server.js server.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(process.env.PORT);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('message', { msg: 'world' });
socket.on('message', function (msg) {
console.log(msg);
console.log('That was a message from the client :)');
});
});
index.html: index.html:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('EDITED');
document.write("test");
socket.on('message', function (msg) {
alert(msg);
//console.log(data);
socket.emit('message', { msg: 'hello there server' });
});
</script>
The server is accepting the message "hello there server" and displaying it correctly in the console; 服务器正在接受消息“你好服务器”,并在控制台中正确显示它; However, when the server sends the message "hello" to the client, the client is supposed to give a pop up alert that should read "hello".
但是,当服务器将消息“ hello”发送给客户端时,客户端应该给出一个弹出警报,该警报应显示为“ hello”。 Instead of the pop up alert saying "hello", it says: [object Object]
而不是弹出警报说“你好”,而是说: [object Object]
Any ideas? 有任何想法吗?
The response is an object: 响应是一个对象:
socket.on('message', function(data) {
alert(data.msg);
I'd consider using console.log
when sending debug messages like this, as you can see the structure instead of just [object Object]
. 在发送这样的调试消息时,我会考虑使用
console.log
,因为您可以看到结构,而不仅仅是[object Object]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.