简体   繁体   中英

Nodejs server/client socket connection with engine.io

I am trying to get a simple socket connection established between an engine.io socket listener which is listening on port 8888 and a javascript client which is running in a plain index.html

It looked rather straight forward to accomplish this task but somehow I am unable to get a xhr-polling client connected properly. It connects, since the client number increases but the onopen event is never triggered on the client side. Instead the client count on the server side just keeps increasing infinitely and the client is never receiving any messages from the server - nor is the server receiving any messages from the client.

It all works perfectly with the websocket transport, but I need xhr-polling to work as well.

app.js

var engine = require('engine.io');
var server = engine.listen(8888);

server.on('connection', function (socket) {
    console.log(server.clientsCount);
    socket.send('never received by client'); // << xhr-polling client does not receive
    socket.on('message', function (msg) {
        if ('echo' == msg) socket.send(msg);
    });
});

index.html

<html>
<head>

<script src="engine.io.js"></script>
<script>
    var socket = eio('ws://localhost:8888/'); << starts polling immediately like crazy
    socket.onopen = function(){
        console.log('never fired'); << never sent to console
        socket.onmessage = function(data){};
        socket.onclose = function(){};
    };
</script>

</head>
<body>
</body>
</html>

client console

GET http://localhost:8888/engine.io/?EIO=2&transport=polling 200 OK 280ms engine.io.js (Zeile 1585)
GET http://localhost:8888/engine.io/?EIO=2&transport=polling 200 OK 1ms engine.io.js (Zeile 1585)
GET http://localhost:8888/engine.io/?EIO=2&transport=polling 200 OK 1ms engine.io.js (Zeile 1585)
GET http://localhost:8888/engine.io/?EIO=2&transport=polling 200 OK 1ms engine.io.js (Zeile 1585)
GET http://localhost:8888/engine.io/?EIO=2&transport=polling 200 OK 0ms engine.io.js (Zeile 1585)
GET http://localhost:8888/engine.io/?EIO=2&transport=polling 200 OK 0ms engine.io.js (Zeile 1585)
GET http://localhost:8888/engine.io/?EIO=2&transport=polling 200 OK 0ms engine.io.js (Zeile 1585)

If your HTML and static files (JS) are server from another domain (localhost:80 for example, as port == another "domain").
Then due to security reasons it might deny WebSockets or other traffic to happen due to CORS reasons.

Use Network tab in Dev Tools of your favourite browser, to check what is going on and if any requests fails as well as their headers.

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