尝试了不同的方法,但数据最多只发送一个或两个客户端。如何将数据发送到连接到服务器的所有客户端?我做错了什么?
Server.js:
var PORT = 3000; var options = { // 'log level': 0 }; var express = require('express'); var app = express(); var http = require('http'); var server = http.createServer(app); var io = require('socket.io').listen(server, options); server.listen(PORT); app.get('/', function (req, res) { res.sendfile(__dirname + '/attantions/templates/.default/template.php'); }); io.sockets.on('connection', function (client) { client.on('attantion', function (data) { try { // Tried so io.sockets.volatile.emit('attantion', data); // And tried so io.sockets.emit('attantion', data); client.emit('attantion', data); client.broadcast.emit('attantion', data ); } catch (e) { console.log(e); client.disconnect(); } }); });
Client.js:
socket.emit("attantion", data); socket.on('attantion', function (data) { pushData(data); });
答案 0 :(得分:0)
有关socket.io消息的不同选项,请参阅此文章
Send response to all clients except sender (Socket.io)
io.sockets.on('connection', function (client) {
client.on('attantion', function (data) {
//client.emit('attantion', data ); // This will send it to only the client
//client.broadcast.emit('attantion', data); // This will send it to everyone but this client
io.emit('attantion', data); // This will send it to all attached sockets.
});
});
修改
我想知道这篇文章是否可以帮到你?
我很好奇如何通过node.js将php文件发送到客户端?你在使用另一个框架吗?
您能展示一下客户端代码的更多内容吗?加载lib和套接字的实例化。