我有一個應用程序接收來自程序的消息。該應用程序接收消息,並將消息廣播給連接的客戶端。現在我在控制檯和控制檯上顯示消息,這個接收器應用程序正在完美接收。但是在客戶端(html頁面),它不會被廣播。當我打開本地主機/結果時,不顯示任何內容。我究竟做錯了什麼?node.js socket.io未廣播到連接的客戶端
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>
您是否嘗試過重新制作的示例? – EMX
它工作得很好。但是,爲什麼我不明白,爲什麼它的工作正常,當按鈕單擊而不是文檔加載觸發發射? – Neo
,因爲onload你應該首先將套接字連接到服務器並設置客戶端套接字事件處理程序。然後在'連接'的客戶端內,你知道這個套接字已經連接上了,所以在這個事件中你可以開始發射。 – EMX