Dynamic Namespaces Socket.IO

后端 未结 5 585
再見小時候
再見小時候 2021-01-30 09:32

How can I use dynamic namespaces in socket.io.

I\'m looking in the (poor) documentation, and it says that namespaces must be used like this:

io.of(\'/news\

5条回答
  •  醉梦人生
    2021-01-30 09:40

    Here is one way. Here is a socket.io subclass I created to solve the problem:

    https://github.com/PencilCode/dynamic.io

    That subclass adds dynamic namespaces as well as virtual hostname support (each host can go into its own namespace tree if you like). That repo has some examples.

    Here is a universal socket.io listener that listens to every namespace requested, and logs a message for every socket that connects. You could listen to a different regexp to listen to any subset of namespaces.

    It works with the standard socket.io client library without any modification.

    var DynamicServer = require('dynamic.io');
    io = DynamicServer({
        host: true,                     // Enable virtual host handling
        publicStatus: true              // Enable /socket.io/status page.
    });
    // Any number of namespace patterns can be set up.
    // This is an example of a single catch-all pattern.
    io.setupNamespace(/.*/, function(nsp) {
        nsp.on('connect', function(socket) {
            console.log('a socket connected on', nsp.fullname());
        });
        nsp.expire(function() {
            console.log(nsp.fullname(), 'is expiring');
        });
    });
    io.listen(8888);
    

提交回复
热议问题