0

我使用 node.js + express + socket.io 在从套接字接收信号后做一些 ajax 事件,有时它工作但有时当同时有多个浏览器请求时失败。这是我的编码:

服务器:

var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server);

server.listen(4000);

io.sockets.on('connection', function(socket){
    socket.on('send message', function(data){
        io.sockets.emit('new message', data);
    });
});

客户:

<script type="text/javascript">
var socket = io.connect();

jQuery(function($){
    socket.on('new message', function(data){
        if(data=='refreshNow'){
            $.ajax({
                type:"get",
                dataType:"json",
                url:"index.php?r=Ajax/TestBlankData",
                success:function(data){
                    console.log('success');
                },
                error: function() {
                    console.log('error');
                },
            });
        }
    });
});

$( "#testing" ).click(function() {
    socket.emit('send message', 'refreshNow');
});
</script>

ajax页面:

public function actionTestBlankData()
{
    echo CJSON::encode(array());
}

安慰:

18 success
4 error
x GET http://localhost:5000/wwwroot/XHS/index.php?r=Ajax/TestBlankJson  jquery.js:8434
    send jquery.js:8434
    jQuery.extend.ajax jquery.js:7986
    (anonymous function) index.php:95
    EventEmitter.emit socket.io.js:634
    SocketNamespace.onPacket socket.io.js:2249
    Socket.onPacket socket.io.js:1931
    Transport.onPacket socket.io.js:1333
    Transport.onData socket.io.js:1304
    websocket.onmessage socket.io.js:2379
4

0 回答 0