[英]nodejs and socketio -Cannot send messages
我想創建一個類似聊天的應用程序,因此開始使用nodejs和socket.io。 為簡單起見(首先,我想了解它的工作原理),我制作了一個向服務器發送消息的按鈕,該按鈕應(以我的新手理解)應更改當前指向該頁面的所有網頁的內容。網址。 我的問題是,發出消息的網頁的內容發生了變化,但指向相同URL的其他網頁的同一段卻什么也沒有發生。
這是我的代碼:
// This is server.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs');
app.listen(8080);
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('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
socket.on('user_event', function (data) {
socket.emit("to_all_users","something has changed");
console.log(data);
});
});
以下是我的HTML(客戶端)文件(僅相關部分):
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('to_all_users', function (data) {
var msgs=document.getElementById("my_messages");
msgs.innerHTML=data;
});
function send_to_server(){
socket.emit("user_event","Here is the new news");
}
</script>
</head>
<body>
<button onclick="send_to_server()">CHECKBUTTON</button>
<p id="my_messages">Here is the messages</p>
What I did:
我在Google-chrome上打開了兩個localhost:8080,然后單擊其中之一的CHECKBUTTON。
What I expected
:兩個選項卡(localhost:8080)中的id = my_messages的段落都將更改為數據-“事情已更改”
What actually happened:
單擊按鈕的段落更改為所需的字符串。 事實證明消息已到達服務器,並且是服務器發出的響應觸發了頁面中的事件以更改段落。 但是其他都沒有發生任何變化(localhost:8080)。
我想念什么? 我在這里從根本上想錯了方向嗎?
更改server.js中的1行
//來自
socket.emit("to_all_users","something has changed");
// 至
io.sockets.emit("to_all_users", "something has changed");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.