我想創建一個類似聊天的應用程序,所以使用nodejs和socket.io開始。爲了簡單起見(首先,我想了解它是如何工作的),我做了一個按鈕來發送消息給服務器,反過來應該(在我的新手理解中)改變當前指向的所有網頁段落的內容URL。我的問題是,我從中發佈消息的網頁內容被更改,但沒有發生任何指向相同URL的其他網頁的相同段落。nodejs和socketio - 無法發送消息
這裏是我的代碼:
// 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:
我開了兩個本地主機:8080我google-chrome並點擊其中一個的CHECKBUTTON。
What I expected
:在兩個標籤ID = my_messages(本地主機:8080)第改變到DATA-「東西已經改變」從那裏我點擊按鈕
What actually happened:
段落變更爲所希望的字符串。它證明消息傳遞給服務器,並且它是服務器發出的響應,它觸發頁面中的事件來更改段落。但是另一個沒有發生(localhost:8080)。
我錯過了什麼?我在這裏從根本上思考錯誤的方向嗎?在server.js
太好了!非常感謝。 –
這對我和其他人會有所幫助,如果你也可以添加一些關於每個人做什麼以及爲特定目的應該使用什麼的信息。 –
哦,幫幫我傑克,我不擅長英語,文檔在這裏http://socket.io/#how-to-use – damphat