当我在EventEmitter中使用它时socketio广播消息

时间:2017-10-27 00:02:22

标签: javascript node.js websocket socket.io

我有网络套接字服务器和http服务器,我想告诉socketio服务器只有在使用EventEmitter类发出事件时才向客户端发出一个消息,问题是当我在浏览器中打开2个标签时我注意到了事件被发送给所有用户(广播)

这两个服务器都是:

const server = require('http').createServer(handler)
    , io = require('socket.io')(server)
    , url = require('url')
    , fs = require('fs')
    , EventEmitter = require('events')
    , emitter = new EventEmitter();

server.listen(3000);

function handler(req, res) {

    var route = url.parse(req.url).pathname;

    if (route === '/') {
        var stream = fs.createReadStream(__dirname + '/index.html');
        stream.pipe(res);
    } else if (route === '/testSocket') {
        var stream = fs.createReadStream(__dirname + '/test.html');
        stream.pipe(res);
        // emit event after 5s, the handler is inside socketio server
        setTimeout( function() {
            emitter.emit('fromEmitterToSocketServer', 'Msg');
        }, 5000);
    } else {
        res.writeHead(404, {"Content-Type": "text/plain"});
        res.end('404');
    }

}

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

    // handle event and then send data to the user
    emitter.on('fromEmitterToSocketServer', function(data) {

        // here I noticed that socketio emit the event to all users
        socket.emit('fromSocketServerToClient', data); 

    });

});

的index.html:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Index</title>
</head>

<body>

    <h1>Index</h1>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
    <script>

        var socket = io('//localhost:3000');

        socket.on('fromSocketServerToClient', function (data) {
            console.log(data);
        });

    </script>

</body>

</html>

的test.html:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Test socketIO</title>
</head>

<body>

    <h1>Test socketIO</h1>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
    <script>

        var socket = io('//localhost:3000');

        socket.on('fromSocketServerToClient', function (data) {
            console.log(data);
        });

    </script>
</body>
</html>

如果我打开两个标签并转到http://localhost:3000http://localhost:3000/testSocket我发现msg已记录到两个标签中

由于

0 个答案:

没有答案