通过socket.io跟踪点击事件

时间:2014-12-03 06:21:50

标签: node.js socket.io

我正在开发一个node.js应用程序,使用快递和socket.io来跟踪用户的点击事件..我的代码段是

app.js

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/user.html');
});

app.get('/admin', function(req, res){
  res.sendFile(__dirname + '/admin.html');
});

io.on('connection', function(socket){
  socket.on('clicked', function(val){
    io.emit('clicked', val);
  });
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

user.html

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
    button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
</style>
    <title></title>
</head>
<body>
    <button id="click">Click Me</button>

    <script>
          var socket = io('http://localhost:3000');
          var count = 0;
          $('#click').click(function(){
            var val = count++;
            socket.emit('clicked', val);
             });
    </script>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
</body>
</html>

admin.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <h2>Total no. of clicks</h2>
    <p id="message"></p>
    <script>
        var socket = io('http://localhost:3000');
        socket.on('clicked', function(val){
            console.log(val);
            $('#message').text(val);
        });
    </script>


<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>

</body>
</html>

我想做的就是显示没有。实时管理页面上的点击次数

我通过控制台进入管理页面的错误是 enter image description here

1 个答案:

答案 0 :(得分:1)

//将您的javascript代码放在这两个库下面

<script src="https://cdn.socket.io/socket.io-1.2.0.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js" type="text/javascript"></script>

<script type="text/javascript">
        var socket = io('http://localhost:3000');
        socket.on('clicked', function(val){
            console.log(val);
            $('#message').text(val);
        });
    </script>