我想用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);
});
});
websocket链接成功之后,操作的上下文是socket对象。io.on('connection', cb)中cb包含的io改为socket
soonfy