我想用websocket来统计在线人数。登陆成功,转到home.html.在home显示在线人数,但是,不停报错
,我接触nodejs不多,选修作业实在有点应付不来,希望得到指导,谢谢
html代码如下:
<!--统计在线人数-->
当前在线人数: <span id="count"></span> <br/>
里面还有:
$(document).ready(function () {
// 创建链接
var socket = io.connect('http://localhost:3000');
socket.on('stats', function(data) {
console.log('Connected clients:', data.numClients);
$('#count').text(data.numClients);
});
});
index.js 代码如下:
var express = require('express');
var router = express.Router();
var path = require('path');
var WebSocket = require('ws');
var WebSocketServer = WebSocket.Server;
var io = new WebSocketServer({
port: 3000
});
var numClients = 0;
//统计人数
io.on('connection', function(socket) {
numClients++;
io.emit('stats', { numClients: numClients });
console.log('Connected clients:', numClients);
socket.on('disconnect', function() {
numClients--;
io.emit('stats', { numClients: numClients });
console.log('Connected clients:', numClients);
});
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…