2013-03-17 60 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"); 
} 
相关问题