javascript - websocket 用于nodejs统计在线人数
PHPz
PHPz 2017-04-11 13:07:13
0
1
1492

我想用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);
    });
});
PHPz
PHPz

学习是最好的投资!

全員に返信(1)
PHPzhong

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

いいねを押す +0
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート