我有一个从程序接收消息的应用程序。该应用程序接收消息,然后将消息广播到连接的客户端。现在,我在控制台上和控制台上显示消息,此接收器应用程序正在完美接收。但是,在客户端(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');
});


result.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>

最佳答案

我将直接从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

10-08 06:33
查看更多