我在socket.io和HTML5之间的问题
Javascript服务器:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
io.on('connection', function(socket){
socket.emit('news','Hello');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
HTML5:
<html>
<head>
<meta charset="UTF-8">
<title>My Title</title>
</head>
<body>
<input type="button" id="getButton" value="Get Rooms">
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$("#getButton").click(function(){
socket.on('news',function(data){
alert(data);
});
});
</script>
</body>
</html>
当我点击按钮(ID:getButton)时,我没有收到警报。服务器正在工作,我可以毫无问题地访问该页面。
Iam目前是socket.io/javascript(昨天安装)的新手,如果你有关于socket.io的信息丰富的网页,请发布此主题下的链接,谢谢。
最好的问候
答案 0 :(得分:0)
您在连接后立即发出新闻消息,因此在您点击按钮时它已经被解雇了。尝试将代码更改为此,您应该会看到警报:
var socket = io();
socket.on('news', function(data) {
alert(data);
});
您可以在按钮上触发事件,如下所示:
服务器强>
io.on('connection', function(socket) {
//socket.emit('news','Hello');
});
// Return the news when it's requested
io.on('giveMeNews', function(socket) {
socket.emit('news', 'Here is your news');
});
<强>客户端:强>
// Listen for the news message
socket.on('news', function(data) {
alert(data);
});
// Request news from the server
$("#getButton").click(function() {
socket.emit('giveMeNews');
)};