带有轮询请求的socket.io泛洪服务器

时间:2017-11-22 10:26:33

标签: javascript node.js websocket socket.io

当我尝试运行我的socket.io应用程序时,客户端上的socket.io只是使用新的和新的连接充斥服务器而不是维护一个:

enter image description here

代码很基本,所以可能出错?

示例代码:

服务器:

requirejs(['http', 'socket.io', 'node-static],
    function (Http, SocketIo, staticServer) {
        const staticHTTP = new staticServer.Server('./');
        var http = Http.createServer(function (request, response) {
            request.addListener('end', function () {
                staticHTTP.serve(request, response);
            }).resume();
        });
        var io = SocketIo(http);

        io.on('connection', function (socket) {
            /// Handle connection
            /// but socket IO keeps creating 5 connections per second
        });
        var port = process.env.PORT || 3000;
        http.listen(port, function () {
            console.log('listening on *:' + port);
        });
});

客户端:

requirejs(["socket.io"], function (io) {
    var socket = io(location.hostname + ":" + location.port);
    ///These events never occur
    socket.on("connect", function () {
        console.log("Connected via websocket.");
    })
    socket.on("disconnect", function () {
        console.warn("websocket ded")
    });
})

1 个答案:

答案 0 :(得分:1)

试试这个......

var socket = io({transports: ['websocket'], upgrade: false});

强制socket.io只使用webSocket并且从不使用HTTP轮询,然后问题就消失了。