【Web前端问题】websocket 用于nodejs统计在线人数

我想用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

const express = require('express');

const http = require('http');

const WebSocket = require('ws');

const app = express();

const server = http.createServer(app);

const io = new WebSocket.Server({ server });

var numClients = 0;

//统计人数

io.on('connection', function(socket) {

numClients++;

socket.emit('stats', { numClients: numClients });

console.log('Connected clients:', numClients);

socket.on('disconnect', function() {

numClients--;

socket.emit('stats', { numClients: numClients });

console.log('Connected clients:', numClients);

});

});

server.listen(3000, function listening() {

console.log('Listening on %d', server.address().port);

});

soonfy

以上是 【Web前端问题】websocket 用于nodejs统计在线人数 的全部内容, 来源链接: utcz.com/a/140910.html

回到顶部