【问题标题】:Node JS: socket.io with multiple childs节点 JS:socket.io 有多个孩子
【发布时间】:2014-04-28 22:41:52
【问题描述】:

我正在使用 Node JS 开发一个服务器,我在其中创建多个使用 chrome 打开 html 的子节点。

app.post('/exeVideo', function(req,res) {
    child = child_process.spawn('chromium-browser', ['RaspMediaVideos.html']);    
    child.on('exit', function() {            
        res.writeHead(200,"0K",{'Content-Type': 'text/plain'});
        res.end(); 
    });
});

这个 Html 有一个与服务器的 socket.io 通信:

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

    app.post('/playVideo', function(req,res) {
        socket.emit("playvideo");
        res.writeHead(200,"0K",{'Content-Type': 'text/plain'});
        res.end();          
    });

    app.post('/pauseVideo', function(req,res) {
        socket.emit("pausevideo");
        res.writeHead(200,"0K",{'Content-Type': 'text/plain'});
        res.end();      
    });

我的问题是,如果我使用上面显示的代码创建 2 个 childs_process,两个 chrome 窗口都可以正常执行,但只有第一个窗口正在处理 socket.io 事件(效果很好)。第二个不响应任何事件:S 我怎样才能让所有孩子都捕获 socket.io 事件?

这里是html处理事件的脚本:

var socket = io.connect('http://localhost:3434');

socket.on("pausevideo", function() {
    player.pause();
});

socket.on("playvideo", function() {
    player.play();
});

感谢您的宝贵时间。

【问题讨论】:

    标签: node.js sockets process


    【解决方案1】:

    您在那些只会发送到调用套接字的函数中调用 socket.emit。试试这样吧。

    app.post('/playVideo', function(req,res) {
        io.sockets.emit("playvideo");
        res.writeHead(200,"0K",{'Content-Type': 'text/plain'});
        res.end();          
    });
    
    app.post('/pauseVideo', function(req,res) {
        io.sockets.emit("pausevideo");
        res.writeHead(200,"0K",{'Content-Type': 'text/plain'});
        res.end();      
    });
    
    
    io.on("connection", function (socket) {
        // Handle Events
    }
    

    【讨论】:

    • 谢谢!没有注意到这个选项的存在,非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多