Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

javascript - NodeJS with Socket.IO delay emitting data

I am using the example from the Socket.IO homepage (http://socket.io/). It works and everything, but there is a huge delay between the time data is sent, and when that data is received on the other end.

I am using XAMPP, I have socket.html in my dir, and navigate to it using "http://localhost/socket.html" in my browser, and I have the server listening on port 8080.

Server:

var io = require('socket.io').listen(8080);

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

HTML File:

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

<body>

</body>
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have found the problem.

In the server I changed:

var io = require('socket.io').listen(8080);

to

var io = require('socket.io', { rememberTransport: false, transports: ['WebSocket', 'Flash Socket', 'AJAX long-polling'] }).listen(8080);

which forces the server to use either WebSockets, Flash Sockets, or long-polling. It wil try to use those in that order. The rememberTransport forces the server and client to forget which connection it used last, and try to connect with the 'transports' above.

On the client side I just pretty much did the same thing. I added:

{ rememberTransport: false, transports: ['WebSocket', 'Flash Socket', 'AJAX long-polling']}

to the socket constructor. So it looked like:

var socket = io.connect('http://localhost:843', { rememberTransport: false, transports: ['WebSocket', 'Flash Socket', 'AJAX long-polling']});

Now it seems to work perfectly.

Thanks guys.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...