【问题标题】:how to set max. of clients of socket io?如何设置最大值。 socket io 的客户端?
【发布时间】:2019-10-26 05:04:01
【问题描述】:

我的服务器只有两个允许连接的客户端。如何在socket.io的两个客户端上设置客户端的最大值? 这就是我的 server.js 的样子:

var path = require('path');
var express = require('express'),
    app = express(),
    http = require('http'),
    socketIo = require('socket.io');

var server = http.createServer(app);
var io = socketIo.listen(server);
server.listen(9000);

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname + 'index.html'));


});
app.use(express.static(__dirname + '/'));

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


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


        socket.broadcast.emit('data', data)
    });

    socket.on('disconnect', function () {
console.log("disconnect")
    });

});

【问题讨论】:

    标签: javascript html socket.io client-server


    【解决方案1】:

    这是未经测试的,但您应该能够检查连接的用户数量并在连接/断开连接时更改它。

    这是一个例子:

    const connectedUsers = 0;
    const maxUsers = 2;
    io.on('connection', function (socket) {
        if(connectedUsers + 1 > maxUsers){ // check if the new connection will exceed the max connections allowed
           socket.disconnect(); // if so, disconnect the user and exit https://stackoverflow.com/a/5560187/11518920
           return;
        }
        connectedUsers++; // otherwise + 1 to the connectedUsers
        socket.on('data', function (data) {
           socket.broadcast.emit('data', data)
        });
       socket.on('disconnect', function () {
           connecteUsers--; // on a disconnected decrease the connectedUsers count
           console.log("disconnect")
        });
    });
    

    【讨论】:

    • 谢谢,有什么技巧可以向第三个用户显示他无法连接到服务器的警报吗?
    • @GermanyDeutschland 在调用断开功能之前,只需向该特定用户发送一条消息。
    • 是的,但是如何发送消息?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多