Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

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);
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...