Code Monkey home page Code Monkey logo

engine.io-client's Introduction

Engine.IO client

Build Status NPM version

This is the client for Engine.IO, the implementation of transport-based cross-browser/cross-device bi-directional communication layer for Socket.IO.

How to use

Standalone

You can find an engine.io.js file in this repository, which is a standalone build you can use as follows:

<script src="/path/to/engine.io.js"></script>
<script>
  // eio = Socket
  const socket = eio('ws://localhost');
  socket.on('open', () => {
    socket.on('message', (data) => {});
    socket.on('close', () => {});
  });
</script>

With browserify

Engine.IO is a commonjs module, which means you can include it by using require on the browser and package using browserify:

  1. install the client package

    $ npm install engine.io-client
  2. write your app code

    const { Socket } = require('engine.io-client');
    const socket = new Socket('ws://localhost');
    socket.on('open', () => {
      socket.on('message', (data) => {});
      socket.on('close', () => {});
    });
  3. build your app bundle

    $ browserify app.js > bundle.js
  4. include on your page

    <script src="/path/to/bundle.js"></script>

Sending and receiving binary

<script src="/path/to/engine.io.js"></script>
<script>
  const socket = eio('ws://localhost/');
  socket.binaryType = 'blob';
  socket.on('open', () => {
    socket.send(new Int8Array(5));
    socket.on('message', (blob) => {});
    socket.on('close', () => {});
  });
</script>

Node.JS

Add engine.io-client to your package.json and then:

const { Socket } = require('engine.io-client');
const socket = new Socket('ws://localhost');
socket.on('open', () => {
  socket.on('message', (data) => {});
  socket.on('close', () => {});
});

Node.js with certificates

const opts = {
  key: fs.readFileSync('test/fixtures/client.key'),
  cert: fs.readFileSync('test/fixtures/client.crt'),
  ca: fs.readFileSync('test/fixtures/ca.crt')
};

const { Socket } = require('engine.io-client');
const socket = new Socket('ws://localhost', opts);
socket.on('open', () => {
  socket.on('message', (data) => {});
  socket.on('close', () => {});
});

Node.js with extraHeaders

const opts = {
  extraHeaders: {
    'X-Custom-Header-For-My-Project': 'my-secret-access-token',
    'Cookie': 'user_session=NI2JlCKF90aE0sJZD9ZzujtdsUqNYSBYxzlTsvdSUe35ZzdtVRGqYFr0kdGxbfc5gUOkR9RGp20GVKza; path=/; expires=Tue, 07-Apr-2015 18:18:08 GMT; secure; HttpOnly'
  }
};

const { Socket } = require('engine.io-client');
const socket = new Socket('ws://localhost', opts);
socket.on('open', () => {
  socket.on('message', (data) => {});
  socket.on('close', () => {});
});

In the browser, the WebSocket object does not support additional headers. In case you want to add some headers as part of some authentication mechanism, you can use the transportOptions attribute. Please note that in this case the headers won't be sent in the WebSocket upgrade request.

// WILL NOT WORK in the browser
const socket = new Socket('http://localhost', {
  extraHeaders: {
    'X-Custom-Header-For-My-Project': 'will not be sent'
  }
});
// WILL NOT WORK
const socket = new Socket('http://localhost', {
  transports: ['websocket'], // polling is disabled
  transportOptions: {
    polling: {
      extraHeaders: {
        'X-Custom-Header-For-My-Project': 'will not be sent'
      }
    }
  }
});
// WILL WORK
const socket = new Socket('http://localhost', {
  transports: ['polling', 'websocket'],
  transportOptions: {
    polling: {
      extraHeaders: {
        'X-Custom-Header-For-My-Project': 'will be used'
      }
    }
  }
});

Features

  • Lightweight
  • Runs on browser and node.js seamlessly
  • Transports are independent of Engine
    • Easy to debug
    • Easy to unit test
  • Runs inside HTML5 WebWorker
  • Can send and receive binary data
    • Receives as ArrayBuffer or Blob when in browser, and Buffer or ArrayBuffer in Node
    • When XHR2 or WebSockets are used, binary is emitted directly. Otherwise binary is encoded into base64 strings, and decoded when binary types are supported.
    • With browsers that don't support ArrayBuffer, an object { base64: true, data: dataAsBase64String } is emitted on the message event.

API

Socket

The client class. Mixes in Emitter. Exposed as eio in the browser standalone build.

Properties

  • protocol (Number): protocol revision number
  • binaryType (String) : can be set to 'arraybuffer' or 'blob' in browsers, and buffer or arraybuffer in Node. Blob is only used in browser if it's supported.

Events

  • open
    • Fired upon successful connection.
  • message
    • Fired when data is received from the server.
    • Arguments
      • String | ArrayBuffer: utf-8 encoded data or ArrayBuffer containing binary data
  • close
    • Fired upon disconnection. In compliance with the WebSocket API spec, this event may be fired even if the open event does not occur (i.e. due to connection error or close()).
  • error
    • Fired when an error occurs.
  • flush
    • Fired upon completing a buffer flush
  • drain
    • Fired after drain event of transport if writeBuffer is empty
  • upgradeError
    • Fired if an error occurs with a transport we're trying to upgrade to.
  • upgrade
    • Fired upon upgrade success, after the new transport is set
  • ping
    • Fired upon receiving a ping packet.
  • pong
    • Fired upon flushing a pong packet (ie: actual packet write out)

Methods

  • constructor
    • Initializes the client
    • Parameters
      • String uri
      • Object: optional, options object
    • Options
      • agent (http.Agent): http.Agent to use, defaults to false (NodeJS only)
      • upgrade (Boolean): defaults to true, whether the client should try to upgrade the transport from long-polling to something better.
      • forceBase64 (Boolean): forces base 64 encoding for polling transport even when XHR2 responseType is available and WebSocket even if the used standard supports binary.
      • withCredentials (Boolean): defaults to false, whether to include credentials (cookies, authorization headers, TLS client certificates, etc.) with cross-origin XHR polling requests.
      • timestampRequests (Boolean): whether to add the timestamp with each transport request. Note: polling requests are always stamped unless this option is explicitly set to false (false)
      • timestampParam (String): timestamp parameter (t)
      • path (String): path to connect to, default is /engine.io
      • transports (Array): a list of transports to try (in order). Defaults to ['polling', 'websocket', 'webtransport']. Engine always attempts to connect directly with the first one, provided the feature detection test for it passes.
      • transportOptions (Object): hash of options, indexed by transport name, overriding the common options for the given transport
      • rememberUpgrade (Boolean): defaults to false. If true and if the previous websocket connection to the server succeeded, the connection attempt will bypass the normal upgrade process and will initially try websocket. A connection attempt following a transport error will use the normal upgrade process. It is recommended you turn this on only when using SSL/TLS connections, or if you know that your network does not block websockets.
      • pfx (String|Buffer): Certificate, Private key and CA certificates to use for SSL. Can be used in Node.js client environment to manually specify certificate information.
      • key (String): Private key to use for SSL. Can be used in Node.js client environment to manually specify certificate information.
      • passphrase (String): A string of passphrase for the private key or pfx. Can be used in Node.js client environment to manually specify certificate information.
      • cert (String): Public x509 certificate to use. Can be used in Node.js client environment to manually specify certificate information.
      • ca (String|Array): An authority certificate or array of authority certificates to check the remote host against.. Can be used in Node.js client environment to manually specify certificate information.
      • ciphers (String): A string describing the ciphers to use or exclude. Consult the cipher format list for details on the format. Can be used in Node.js client environment to manually specify certificate information.
      • rejectUnauthorized (Boolean): If true, the server certificate is verified against the list of supplied CAs. An 'error' event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. Can be used in Node.js client environment to manually specify certificate information.
      • perMessageDeflate (Object|Boolean): parameters of the WebSocket permessage-deflate extension (see ws module api docs). Set to false to disable. (true)
        • threshold (Number): data is compressed only if the byte size is above this value. This option is ignored on the browser. (1024)
      • extraHeaders (Object): Headers that will be passed for each request to the server (via xhr-polling and via websockets). These values then can be used during handshake or for special proxies. Can only be used in Node.js client environment.
      • onlyBinaryUpgrades (Boolean): whether transport upgrades should be restricted to transports supporting binary data (false)
      • forceNode (Boolean): Uses NodeJS implementation for websockets - even if there is a native Browser-Websocket available, which is preferred by default over the NodeJS implementation. (This is useful when using hybrid platforms like nw.js or electron) (false, NodeJS only)
      • localAddress (String): the local IP address to connect to
      • autoUnref (Boolean): whether the transport should be unref'd upon creation. This calls unref on the underlying timers and sockets so that the program is allowed to exit if they are the only timers/sockets in the event system (Node.js only)
      • useNativeTimers (Boolean): Whether to always use the native timeouts. This allows the client to reconnect when the native timeout functions are overridden, such as when mock clocks are installed with @sinonjs/fake-timers.
    • Polling-only options
      • requestTimeout (Number): Timeout for xhr-polling requests in milliseconds (0)
    • Websocket-only options
      • protocols (Array): a list of subprotocols (see MDN reference)
      • closeOnBeforeunload (Boolean): whether to silently close the connection when the beforeunload event is emitted in the browser (defaults to false)
  • send
    • Sends a message to the server
    • Parameters
      • String | ArrayBuffer | ArrayBufferView | Blob: data to send
      • Object: optional, options object
      • Function: optional, callback upon drain
    • Options
      • compress (Boolean): whether to compress sending data. This option is ignored and forced to be true on the browser. (true)
  • close
    • Disconnects the client.

Transport

The transport class. Private. Inherits from EventEmitter.

Events

  • poll: emitted by polling transports upon starting a new request
  • pollComplete: emitted by polling transports upon completing a request
  • drain: emitted by polling transports upon a buffer drain

Tests

engine.io-client is used to test engine. Running the engine.io test suite ensures the client works and vice-versa.

Browser tests are run using zuul. You can run the tests locally using the following command.

./node_modules/.bin/zuul --local 8080 -- test/index.js

Additionally, engine.io-client has a standalone test suite you can run with make test which will run node.js and browser tests. You must have zuul setup with a saucelabs account.

Support

The support channels for engine.io-client are the same as socket.io:

Development

To contribute patches, run tests or benchmarks, make sure to clone the repository:

git clone git://github.com/socketio/engine.io-client.git

Then:

cd engine.io-client
npm install

See the Tests section above for how to run tests before submitting any patches.

License

MIT - Copyright (c) 2014 Automattic, Inc.

engine.io-client's People

Contributors

3rd-eden avatar adrai avatar albertyfwu avatar alexlmeow avatar asdfryan avatar binlain avatar cadorn avatar crzidea avatar darrachequesne avatar defunctzombie avatar dependabot[bot] avatar digawp avatar dvv avatar kkoopa avatar lpinca avatar mokesmokes avatar mokesmokes2 avatar nkzawa avatar paradite avatar plievone avatar rase- avatar rauchg avatar raynos avatar ruxkor avatar sanemat avatar sergioramos avatar sweetiesong avatar timmak avatar tj avatar tootallnate avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

engine.io-client's Issues

Different transports should be tuned for connection loss

Some experiments:

  1. XHR-polling, pull the cord: ping timeout in 60 secs. The good thing is that socket.send will error and disconnect immediately, so disconnect is easy to see when the user takes an action, or with a quick ping after a browser wakeup. Reconnecting seems easy, as the socket.open errored quickly when the network was down, so it could be repeated until success. (Haven't tried with proper network reachability issues but browser timeouts are usually reasonable.)
  2. JSONP, pull the cord: ping timeout in 60 secs. Unfortunately there are no errors coming from this transport. One will have to use custom RPC timeouts to detect that the connection is down. Also reconnecting is pain, as the socket.open does not give errors and hasn't got any timeouts, so it has to be opened with serial timeouts, clearing the last etc. Seems very easy to get stuck.
  3. WS, pull the cord: ping timeout in 60 secs. Surprisingly also here the transport is very quiet, and even socket.send seems to succeed (no errors, proper readystate, websocket.bufferedAmount stays at zero). I suspect that this 60 secs timeout will bite many, as things will seem unresponsive until timeout, disconnect and reconnect. WS transport is so lightweight and quick to establish, that quite quick heartbeats can be used, and a custom RPC call with a short timeout can be sent after browser wakeup etc. 60 secs ping timeout for websocket transport seems very bad, as reconnecting is so easy.

These are mostly application-level observations, but perhaps some transports could be tuned to ease the pain (I was very surprised by xhr vs. websockets)

Is `make test-browser` supposed to run in IE?

Firefox, Chrome run fine, IE8 gives me this:

ใƒกใƒƒใ‚ปใƒผใ‚ธ: ใ‚ชใƒ–ใ‚ธใ‚งใ‚ฏใƒˆใงใ‚ตใƒใƒผใƒˆใ•ใ‚Œใฆใ„ใชใ„ใƒ—ใƒญใƒ‘ใƒ†ใ‚ฃใพใŸใฏใƒกใ‚ฝใƒƒใƒ‰ใงใ™ใ€‚
ใƒฉใ‚คใƒณ: 4432
ๆ–‡ๅญ—: 3
ใ‚ณใƒผใƒ‰: 0
URI: http://192.168.0.1:3000/support/mocha.js

In other words: object does not support property or method in mocha.js:4432

Should it run?

Document a preferred way to reconnect

To retain config and listeners, is it ok to reconnect by setting socket.id = null and then socket.open()? Otherwise the id will be sent with the request as query.sid, and it might be missing from the this.clients in Server.prototype.verify (and response 500 results, might be more appropriate with 404 or 410).

JSONPPolling.doWrite() perhaps funny

The logic in JSONPPolling.doWrite is clever. But the flow as now may be a bit funny as I understand it. On first doWrite, the form is created, its result target is set to a specific name, and it is appended to DOM for the rest of the session. Then an iframe of that name is created and appended to DOM for the request. Then the form is submitted, and the onload handler is set on the iframe to be triggered as the server responds with 'ok' which will be loaded to the target iframe.

But now in the onload handler, you callback the success but also remove the old one and create a new one? This is then removed and created anew on next doWrite. But perhaps this is intentional, preventing memory leaks or late triggers to nonexisting iframe? Ok if so. :)

And the synchorization of script tag and a form submit is quite hazy to me, hopefully there are no weird conditions there (I know this is the least common denominator transport, but still wondering). Good work in any case!

Improve `parseUri`

localhost:3000 should work. Right now localhost is considered protocol.

IPV6

i cannot connect between ipv6 addresses using engine.io client and engine.io
is use the ipv6 in [] backets and a port (9999 in the example)

and the transport.uri() also returns the correct uri:
ws://[aaaa:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa]:9999/engine.io/default/?uid=79968139529235726730246097&transport=websocket

i also tried updating the parseUri in utils.js according to this post and the parsing seems to work:

// socketio/socket.io-client#260
var re = /^(?:(?![^:@]+:[^:@\/]@)([^:\/?#.]+):)?(?://)?((?:(([^:@])(?::([^:@]))?)?@)?([[^\/?#]]|[^[][^:\/?#])(?::(\d))?)(((/(?:^?#)/?)?([^?#\/]))(?:?([^#]))?(?:#(.))?)/;

still, no connect is happening :(

Ping timers continue to live on after socket has been closed

The timers set in ping() and onHeartBeat() continue to live on, even if the socket is closed. I think these are causing my unit tests (running engine.io-client inside node) to never complete.

Should onClose clean these up?

clearTimeout(self.pingIntervalTimer);
clearTimeout(this.pingTimeoutTimer);

node2node connection is down in first minutes

When i connect two nodes in first minute i have error message on client
and in next minute i have closed connection from client side.
This time is not depend on messages size and send frequlity

code:

  1. server side
var engine = require('engine')
  , server = engine.listen(80)

var counter = 0;
function getTimeMeasurementJavaScript(name, func){
      timeStart=new Date();
      func();
      totalTime = (new Date - timeStart);
      console.log(timeStart + " > " + name + ":" + totalTime + "msec" + " " + counter++);
}

server.on('connection', function (socket) {

  var execf = function(){
      getTimeMeasurementJavaScript("test",function(){
      socket.send("fff");
    })
  }

  setTimeout(execf,10)
  socket.on('message', function (data) {
        setTimeout(execf,100)
  })

  socket.on('close', function (data) {
        console.log ("connection closed")
  })  

  socket.on('error', function (data) {
        console.log ("error")
  })
});
  1. client side
var eio = require('engine.io-client')

var socket = new eio.Socket({ host: 'localhost', port: 80 });

socket.on('open', function () {
    console.log("open client connection")

  socket.on('message', function (myJSONText) {
        time=new Date();  
        console.log(" " + time + "  message=" + myJSONText)
        socket.send("ok")
    });

    socket.on('close', function () {
        console.log("connection is closed")
    });

    socket.on('error', function (data) {
        console.log ("error")
    })
});

and a question:
how i can trace connection info ?

engine.io.js generated file has invalid require paths

So the engine.io.js file that is generated with the new Makefile build contains invalid require paths.

So it has:
eio = require('engine.io-client');

But it's registered with:
require.register("lib//engine.io-client.js"

Which when included in the browser causes an error:
failed to require "engine.io-client"

It also appears as if it's maybe getting confused with the transports subdirectory as well?

XMLHttprequest imposes a hard limit on the maximum number of connections per host

I was writing some tests against remote hosts rather than localhost, and realized that there is a hard cap of 5 after which messages will no longer be received and sent correctly when using engine.io-client from Node.

The cap exists because of http://nodejs.org/api/http.html#http_http_request_options_callback where the default agents agent.maxSockets is 5.

Since all transports start as http connections, this cap applies to connections that are made simultaneously during a short time even if they use the websockets protocol later on.

The easy way to replicate this is to write a engine.io server that echos back to all connected clients.

Once you have about 3-4 client connections, messages are no longer echoed back to all of the connected clients - only a subset of clients will receive messages back. The rest of the connections do not work correctly.

There is a code path in Node core that removes http connections that have been upgraded to websockets from the pool, but since the initial handshake is still done by xmlhttprequest, doing multiple connections quickly (as in, in a test case that uses multiple engine.io instances to test server internal logic), the limitation still applies.

The fix is simple: https://github.com/driverdan/node-XMLHttpRequest/blob/master/lib/XMLHttpRequest.js#L358

add { agent: false } to disable the connection limit per host.

I'm filing this issue with XMLHttpRequest as well. Hopefully, this issue can be resolved. Once the agent connection limitation has been removed, engine.io-client will need to bump up the version of xmlhttprequest to resolve the issue.

Corrupt repo

On cloning engine.io-client, doing git submodule init will result in No submodule mapping found in .gitmodules for path 'support/web-socket-js'

Is the module still being used, as I do not see an .gitmodules?

Evaluate whether browser sleep needs to be taken into account

In some places, such as pingTimeout, long setTimeouts are used (default 60 seconds for long polling). When the browser sleeps, such as when Android browser is backgrounded or screensaver kicks, the javascript execution is paused, but also the timers will be paused. When the browser execution continues again after sleep, the timers continue as if nothing happened, so that 60 seconds can be much longer. One should evaluate whether this should be detected, or if server timeouts such as pingInterval (default 25 secs) etc will take care of any issues. See (http://googlecode.blogspot.fi/2009/07/gmail-for-mobile-html5-series-using.html) for example -- the code examples have errors, but you get the point.

Also a related issue to be evaluated is browser suspends and wakeups on machine suspend/sleep, as I remember that with some libraries on long polling one can get errors from the network stack during suspend/wakeup, as the different layers can be started on different order. These things can be annoying. Do these things affect engine.io, have you seen any issues?

consider making websocket transport consistent to others

Needs to measure what's the fastest -- 10xsend('A'), or 1xsend('AAAAAAAAAA').
And what is more reliable, at least virtually, a priori.

That's how I monkey patch the client, so far:

eio.transports.websocket.prototype.onData = function (data) {
  data = eio.parser.decodePayload(data)
  for (var i = 0, l = data.length; i < l; i++) {
    this.onPacket(data[i])
  }
};
eio.transports.websocket.prototype.write = function (packets) {
  this.socket.send(eio.parser.encodePayload(packets));
};

[spec] rename session id

Consider renaming session id to connection id to avoid confusion. This is something that a lot of socket.io users are currently struggling with, they assume that the id is retrained across multiple connections while this is only used to identify the current connection.

JSONP broken

JSONP Polling is not working at its current state. This apparently is because of several reasons, one of them being the assignment of a value attribute to a textarea.

Socket#close error

OSX 10.7.5, Chrome 23.0.1271.101

engine.io.js:2358

 function initIframe () {
    if (self.iframe) {
      self.form.removeChild(self.iframe);
Uncaught Error: NOT_FOUND_ERR: DOM Exception 8
    }

app.js:

var express = require('express')
  , app = express().use(express.static(__dirname + '/public'))
  , http = require('http').createServer(app).listen(1337)
  , server = require('engine.io').attach(http, { transports: ['polling'] })
  ;

server.on('connection', function(socket) {
  console.log('connection');
  socket.on('message', function(message) {
    console.log('message: ' + message);
    socket.send('message: ' + message);
  });
});

public/index.html:

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Socket#close error</title>
</head>
<body>
  <script src="engine.io.js"></script>
  <script>
    var socket = new eio.Socket('ws://localhost:1337');
    socket.on('open', function() {
      console.log('open');
      socket.send('test');
    });
    socket.on('message', function(data) {
      console.log(data);
      socket.close();
    });
  </script>
</body>
</html>

edit: this only happens when i specify the polling transport, and only if i close the connection after receiving a message; closing in the open callback does not produce the error

IE9 cache issues

Hi,
Using latest (b5aba68) engine.io and associated (78f2471) client,
i get a failure with IE9 :

engine-client:socket creating transport "polling" +0ms 
engine-client:socket socket receive: type "open", data "{"sid":"3653182132859437","upgrades":["websocket"],"pingTimeout":60000}" +98ms 
engine-client:socket socket open +2ms 
engine-client:socket starting upgrade probes +2ms 
engine-client:socket probing transport "websocket" +1ms 
engine-client:socket creating transport "websocket" +1ms 
engine-client:socket socket receive: type "ping", data "undefined" +24s 
engine-client:socket flushing 1 packets in socket +0ms 
engine-client:socket socket close with reason: "ping timeout" +1.0m 
engine-client:socket socket closed prematurely - aborting probe +0ms 
SCRIPT5007: Unable to get value of the property 'close': object is null or undefined 
engine.io.js, line 1184 character 3

However, if i set cache settings to "every time i visit the web page" :

engine-client:socket creating transport "polling" +0ms 
engine-client:socket socket receive: type "open", data "{"sid":"1990083178490188","upgrades":["websocket"],"pingTimeout":60000}" +40ms 
engine-client:socket socket open +0ms 
engine-client:socket starting upgrade probes +0ms 
engine-client:socket probing transport "websocket" +1ms 
engine-client:socket creating transport "websocket" +0ms 
engine-client:socket socket receive: type "ping", data "undefined" +24s 
engine-client:socket flushing 1 packets in socket +0ms
engine-client:socket socket receive: type "ping", data "undefined" +24s 
engine-client:socket flushing 1 packets in socket +0ms

The second ping is eaten by IE ?!?

engine.io.js and strict mode?

Constructions like global = this result in effect in global = {}, not global = window for modern browsers (?). At least for Google Chrome 16.0.912.63 on 32-bit Linux.
This results in wrong feature detection and breaks the logic.

race condition when polling and upgrading

if there is an ongoing polling request and the client is not receiving any data, the upgrade blocks until the client gets a response on the poll, usually a ping packet. this makes the usage of websockets difficult, if the server is not continously sending messages.

this behavior can be observed more often if connecting to a remote server; it almost never happens if connecting via localhost in my tests.

tracebacks:

first part:

debug  : polling
debug  : xhr poll
debug  : sending xhr with url http://.../engine.io?uid=944483157247398450060002506&transport=polling&sid=7954197634546385 | data null
debug  : probe transport "websocket" opened - pinging
debug  : probe transport "websocket" pong - upgrading
debug  : pausing current transport "polling"
debug  : we are currently polling - waiting to pause

(after 20 seconds)

debug  : polling got 1:2
debug  : socket receive: type "ping" | data "undefined"
debug  : pre-pause polling complete
debug  : paused
debug  : changing transport and sending upgrade packet
debug  : clearing existing transport

Validate whether url timestamping is needed for most browsers

On my brief testing, even latest Chromium and Firefox (on Ubuntu) needed timestamping to prevent unneccessary looping due to browser caching when xhr-polling. It was visible only when debugmode was on, firebug etc showed only successful requests as usual, but there were tens and even hundreds of "shadow responses" flowing in the debug log for each socket.send.

Remember last actively working transport.

Back in the days of Socket.IO 0.6 we used a cookie to remember the current transport, so that we could re-use that information and skip some of the downgrading steps. It was later removed because it was not working.. But it was just poorly implemented as it deleted the complete list of available transports instead of re-ordering it and adding the last know transport on top.

We could be implementing the same in engine.io where the last known working (received and sends messages without issues) is remembered and use as the next transport to upgrade to after the initial connection has been established.

Introduce `EIO` qs

EIO={protocol version}

should be sent along in every request's query string.

This goes with a SPEC.md change, but no protocol revision bump since it's not necessarily breaking.

xdomain requests are used unneccessarily, omitting cookies

I upgraded to 0.4.x and wondered quite a while why cookies were not transferred for same domain requests (on default port 80, omitting port from the url). The culprit was that eio used xdomain requests for the same domain, despite the good fixes earlier. I will look into this. On the other hand, decreasing the header size by omitting cookies could be feature too, but xdomain doesn't work on all browsers.

remove browserbuild dependency

I don't think it is used in the project anymore.

Also, update debug to 0.7.0 would be nice for those using bundling tools as 0.7.0 has the browserify field :)

location.port can be an empty string and cause fallback to jsonp

There are a couple of places where global.location.port != opts.port is compared. As opts.port is defaulted to 80, but location.port can be an empty string (in Nokia N8, for example in my brief testing), this will cause the crossdomain flag to be set. And as xhr cors won't work on that phone, it will unneccessarily fall to jsonp transport. Xhr transport works otherwise in that phone, for same origin. So comparisons should be made only if (global.location.port). But I haven't tested https.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.