2011-10-01 40 views
0

我正在嘗試一個WebSocket的例子來開發一個簡單的聊天。WebSockets與node.js

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 + '/test.html', 
    function (err, data) { 
     if (err) { 
     res.writeHead(500); 
     return res.end('Error loading index.html'); 
     } 

    res.writeHead(200); 
    res.end(data); 
    }); 
} 

test.html

<script src="/socket.io/socket.io.js"></script> 
<script> 
var socket = io.connect('http://localhost'); 

socket.on('connect', function() { 
    alert('<li>Connected to the server.</li>'); 
}); 

socket.on('message', function(message) { 
    alert(message); 
}); 

socket.on('disconnect', function() { 
    alert('<li>Disconnected from the server.</li>'); 
}); 

function sendF(){ 
    var message = "Test"; 
    socket.send(message); 
    alert('Test Send');  
} 

test.html我也有一個簡單的按鈕,onClick呼叫sendF

如果我嘗試一下,當我連接,發送和斷開連接時,我的瀏覽器上會看到一條警告消息,並且如果我檢查控制檯,就會看到消息。

但是我無法從服務器接收到相同的消息,以便在瀏覽器中顯示它!我認爲socket.on('message'...不適合我!

+0

我沒有使用socket.io的經驗,但WebSockets服務器不應該返回HTML標頭和內容,就像你正在做的一樣。你確定你正在創建一個WebSockets服務器嗎? – pimvdb

+0

socket.io不一定會創建webSockets。 Socket.io找到最好的協議,如長輪詢,並使用它。 – EhevuTov

回答

2

您的server.js缺少事件偵聽器。它也缺少你在瀏覽器中發送消息的地方。

io.sockets.on('connection', function (socket) { 
    console.log('user connected'); 
    socket.send('hello world'); 
    socket.on('disconnect', function() { 
    console.log('user disconnected.'); 
    }); 
    socket.on('message', function (data) { 
    console.log(data); 
    }); 
}); 
相關問題