2013-03-17 78 views
3

如何使用html5中的按鈕發送消息?如何使用socket.io觸發消息?

這裏是我的代碼:

服務器:

var io = require('socket.io').listen(72); 


io.on('connection', function(client){ 
    client.send('{"success": 1}'); 
    client.on('message', function(data) { 
     console.log('Client:', data); 
    }); 
    client.on('disconnect', function() { 
     console.log('Goodbye'); 
    }); 
}); 

客戶端:

<!DOCTYPE html> 
<html> 

<head> 
<script src="http://192.168.0.102:72/socket.io/socket.io.js"></script> 
<script> 
var socket = io.connect('http://192.168.0.102:72'); 
function doit(){ 
    socket.on('message', function(data) { 
    socket.send("hi there"); 
    }); 
} 
</script> 

</head> 

<body> 
    <button name="Klickme" type="button" onclick="doit();">On!</button> 
    <button id="off" type="button" onclick="close();">Off!</button> 
</body> 

</html> 

我讓我的客戶機/服務器上沒有錯誤,但我不得到的消息要麼。有人可以給我一個提示嗎?謝謝!!!

回答

2

當你想收聽從服務器發送的事件,如果你想發送一條消息,你應該使用emit代替on用於:

socket.emit('message', { my: 'data' }); 
+0

作品!非常非常感謝你! – goetzmoritz 2013-03-17 14:11:25

0

您的客戶端從服務器時,等待message您單擊該按鈕(在發送hi there之前)。但是,只要頁面加載並且客戶端連接到服務器,服務器就會立即發送消息。這是唯一的消息服務器發送。所以客戶端不斷等待來自服務器的消息。將doit()更改爲此

function doit(){ 
    socket.send("hi there"); 
} 
相關問題