简体   繁体   中英

Socket io heartbeat is not emitting

when i try to communicate with my socket io, the connection is established and the websocket writing is taking place, but the hearbeat is not getting emitted on the server ..so im not receiving anything on the client side. but when i disconnect and connect the server again, the old written message is getting emitted. please help me through this. thank you I have tried with different port numbers, but its not working.

app.js (Server):

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

server.listen(3000);

app.get('/', function(req, res){
    res.sendfile(__dirname + '/index.html');
});


io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
  console.log("Connected");
  });
});

index.html (Client)

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect();
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

Socket.io might work unstable because of firewall or antivirus. This is actually a problem of WebSockets.

To solve this you may try to exclude WebSockets from the transports between client and server and specify on server side just XHR long polling and JSONP (as these two are the most stable):

io.set('transports', ['xhr-polling', 'jsonp-polling']);

I would also recommend to take a look at Engine.io . This framework is written by Socket.io author as the alternative, which works more stable.

The trick is following:
While Socket.io tries to connect via WebSockets first (when this attempt is fail, user will have to wait about 10 sec to switch to another transport), Engine.io tries to connect via XHR (which works in 100% cases), and meanwhile tries WebSocket connection, and if success - switching to WebSockets occurs.

Edit: Socket.io version 1.0+ is built on the top of Engine.io, so it has now all the benefits described above.

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