【问题标题】:node.js socket.io not broadcasting to the connected clientsnode.js socket.io 没有广播到连接的客户端
【发布时间】:2018-01-09 06:27:17
【问题描述】:

我有一个从程序接收消息的应用程序。此应用程序接收消息,然后将消息广播到连接的客户端。现在我在控制台和控制台上显示消息,这个接收器应用程序正在完美接收。但是在客户端(html 页面)上,它没有被广播。当我打开 localhost/result 时,没有显示任何内容。我做错了什么?

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var EventHubClient = require('azure-event-hubs').Client;
var connectionString = 'connection string';

const bodyParser = require('body-parser')

app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())

var printError = function (err) {
    console.log(err.message);
};

var result;

var printMessage = function (message) {
    console.log('Message received: ');
    result = JSON.stringify(message.body);
    obj = JSON.parse(result);
    console.log('message:' + result)

    console.log('');
};

count =0;

app.get('/result', function(req, res){

  res.sendFile(__dirname + '/result.html');
});


io.on('connection', function(socket){
  console.log('user connected');

  socket.on('chat message', function(msg){

     io.emit('chat message', result);
     console.log("This is id in the sock' section" + check_id);
  }); 
  socket.on('disconnect', function(){
    console.log('user disconnected');
      socket.removeAllListeners('disconnect');
      io.removeAllListeners('connection');
  });
});

var client = EventHubClient.fromConnectionString(connectionString);
client.open()
    .then(client.getPartitionIds.bind(client))
    .then(function (partitionIds) {
        return partitionIds.map(function (partitionId) {
            return client.createReceiver('$Default', partitionId, {     'startAfterTime' : Date.now()}).then(function(receiver) {
                console.log('Created partition receiver: ' + partitionId)
                receiver.on('errorReceived', printError);
                receiver.on('message', printMessage);
            });
        });
    })
    .catch(printError);


http.listen(3000, function(){
console.log('listening on *:3000');
});

结果.html

<html>
  <head><title>Hello world</title></head>
  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();
  //  socket.emit('chat message')


    socket.on('chat message',function(msg){

        socket.emit('chat message',msg);
        document.write('hello world');
        document.write(msg);
    });
  </script>
</html>   

【问题讨论】:

  • 你试过重新制作的例子吗?
  • 它工作正常。但是为什么我不明白为什么在单击按钮而不是文档加载时触发发射时它工作正常?
  • 因为 onload 您应该首先将套接字连接到服务器并设置客户端套接字事件处理程序。然后在“连接”的客户端中,您知道套接字现在已连接,因此在该事件中您可以开始发射。
  • 如果我已经解决了您的原始问题,请记住将其标记为已解决。 :)

标签: html node.js socket.io broadcastreceiver broadcast


【解决方案1】:

我会直接从printMessage 函数发送它:

function printMessage(message) {
 result = JSON.stringify(message.body);
 console.log('[message]',result);
 io.sockets.emit('chat message',result);
}

并记得修改您的客户端 (result.html),使其不会产生无限循环:

<script>
var socket=io();
socket.on('chat message',function(msg){
 console.log(msg); //alert(msg);
 document.write(msg);
});
</script>

编辑:

您如何包含 socket.io.js 脚本?

<script src="/socket.io/socket.io.js"></script>

尝试指定服务器地址socket.connect('localhost:3000');

I made this working example for you


重新编辑: I remade the working example for you, this time I added a client-server emission that bounces back to all connected clients.

【讨论】:

  • 添加了一个工作示例gist
  • 谢谢你的回答,但它似乎仍然不起作用。当我做 io.on('connection...) 并打印一些东西时,它会起作用。但是,当我这样做时,socket.on('chat message...) 它不起作用。
  • 希望re-made example with client-server emission 能帮助你找出你做错了什么......祝你好运:)
猜你喜欢
  • 2017-05-26
  • 2020-03-12
  • 1970-01-01
  • 2016-07-21
  • 1970-01-01
  • 2012-01-25
  • 1970-01-01
  • 1970-01-01
  • 2012-06-23
相关资源
最近更新 更多