简体   繁体   中英

socket.io flood server with polling requests

When I try to run my socket.io application, socket.io on client side just floods the server with new and new connections instead of maintaining one:

在此处输入图片说明

The code is pretty basic, so what could be wrong?

Sample code:

Server:

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);
        });
});

Client:

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")
    });
})

Try this...

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

which forces socket.io to ONLY use a webSocket and never use HTTP polling, then the problem disappears.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM