Chrome & Safari revert to xhr-polling rather than websockets with socket.io - javascript

I have a problem with websockets and socket.io. When I try to connect to my node server with socket.io it initially connects using websockets but when reverts to jsonp-polling shortly after.
This is the output from the node sever when I connect:
8 Jun 07:01:15 - Initializing client with transport "websocket"
8 Jun 07:01:19 - Initializing client with transport "jsonp-polling"
8 Jun 07:01:19 - Client 16630339180119336 connected
This happens in Chrome & Safari.
I have updated to the latest socket.io version 0.6.17 and am running node 0.4.7.
I have tried deleteing my cookies and cache as suggested on github and SO, however the problem remains. Also, when I try to force websockets it never fully connects with a session ID.
Does anyone have any ideas?

Websocket API is not supported by default in all the browsers at the moment (as per my knowledge) it should work on chromium though try testing it on chromium or firefox(after editing the default settings)and see if that still reverts to XHRPolling.
I am running it on a different IP as I need to run node on port 80 which causes conflict on my web server with Apache. Can websockets/flashsockets not be use cross-domain?
Now there might be 2 different reasons for the bug from here
Web/Flash Sockets will not let u connect to the node.js client unless either u specify a differnt port like 81 or u specially specify apache to proxy the incoming request to Node.
an easy solution could be writing the Node.js based HTTP server to just relay data from Apache (and setting Apache to run on a differnt port then 80)
This link tells how to do that... in this process you can make Node.js do something like check if the request is from a websocket/httpbrowser if thats an http browser forward the request to Apache if not ie if thats from web/flash sockets then handle the socket accordingly. or as commented on the question. Specify APACHE to proxy to Node.js.
Flashsockets require you to serve a crossdomain policy file on port 843 are you sure you are providing a cross domain file? (I think socket.io has inbuilt functionality to do that but still its always good to check.)
As told on the socket.io main website
In order to provide realtime connectivity on every browser, Socket.IO selects the most capable transport at runtime, without it affecting the API.
WebSocket
Adobe® Flash® Socket
AJAX long polling
AJAX multipart streaming
Forever Iframe
JSONP Polling
It's pretty clear that it will revert to AJAX Long Polling if websockets are disabled and Adobe Flash Socket fails to connect (this might be due to the unavailability of the policy file).
Here's a sample code for the cross domain file which you can include in your code and see if that makes your server run with websockets.
var net = require("net");
// Node.js
var Policy = net.createServer(function(socket)
{
socket.setEncoding('utf8');
socket.on('connect',function(){
console.log("Policy Request");
socket.end("<?xml version=\"1.0\"?><!DOCTYPE cross-domain-policy SYSTEM \"/xml/dtds/cross-domain-policy.dtd\"><cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\" secure=\"false\"/></cross-domain-policy>");
});
});
Policy.listen(843);

Related

Websockets not working on at least one machine

I have an application that uses websockets.
Web server is glassfish 4.1.1 and we are using #ServerEndpoint for the websockets implementation on a server side.
In all computers everything worked fine up to the date, when on one laptop of some customer we got an error (he uses Google Chrome):
failed to execute 'send' on websocket: Still in CONNECTING state
At that computer this error appears permanently, blocking every functionality that concerns websockets.
We do not setup specific port for websockets. So I assume they are using default one - 80. Other pages loaded successfully (so, our website is accessible from that laptop).
Do you have any key of where to dig? Why only one laptop fails?
Is it needed to provide more information?
Thank you in advance!
Could be many things:
Firewall
Anti-virus
Chrome flag (like running: chrome.exe --disable-web-sockets)
Virus/malware
Man-in-the-middle (MitM)
I suggest to install Firefox. If Firefox has no issues there, then Chrome surely has issues.
I had the same problem. Check what is the port that you try to connect from frontend app (your socket has to be asigned to a port). My WS server was listening on PORT 8080 and some users had outgoing port blocked. I made a proxy from 80 to 8080 and now all users have access.

connect to C# server from javascript

Is it possible to create a javascript program that connect to a simple C# server using a simple socket and not a WebSocket.
can you help me with a sample.
There is no standard way to make a TCP connection from Javascript code running in a web browser. (See the answer by #Johannes Hahn)
To communicate between your client and server, consider Microsoft's SignalR library. It is designed to allow a Javascript program, running in the browser, to communicate with a C# server. SignalR will use websockets; however, it will continue to work if websockets are not available by falling back to other transports. You can also specify transports, if you need to prevent it from attempting to use websockets.
SignalR connection starts as HTTP, and is then promoted to a WebSocket connection if it is available. WebSocket is the ideal transport for SignalR, since it makes the most efficient use of server memory, has the lowest latency, and has the most underlying features (such as full duplex communication between client and server), but it also has the most stringent requirements: WebSocket requires the server to be using Windows Server 2012 or Windows 8, and .NET Framework 4.5. If these requirements are not met, SignalR will attempt to use other transports to make its connections.
Also, be aware that if your Javascript is not running in a web browser, you can make regular network connections. For example, a Javascript application running on Node.js.
It seems that at least Firefox is supposed to know about socket, see https://developer.mozilla.org/en-US/docs/Web/API/TCP_Socket_API. But (taken from the same source) TCP or UDP sockets are not part of any standard and therefore likely either unsupported or completely different in other browsers.
In principle no. For security reasons browsers only allow a limited set of protocols. Chrome has a socket API, but that is not standard - https://developer.chrome.com/apps/sockets_tcp. There are solutions which use a WebSocket connection to a server which then establishes a TCP socket connection, e.g. https://github.com/kanaka/websockify, http://artemyankov.com/tcp-client-for-browsers/, so if you can't add WebSocket directly to the server you may want to check these out.

Socket.io 1.x: use WebSockets only?

We are developing a web application that will run only on modern browsers (IE10+) for different reasons.
One of the features we implemented is Socket.io 1.x. However, by default the Socket.io client tries to support older browsers, so it starts a connection with long polling and then updates that to WebSockets. This is a waste of time and resources, given we know for sure the browser supports WS.
I've searched around, and I can only find this wiki page which, however, is about Socket.io 0.9.
Eventually, I found the documentation for engine.io-client (on which Socket.io-client is based on the 1.x branch). This is the code that I wrote and seems to be working. However, I would like to know if it's correct or if I'm doing something wrong:
io.connect('https://...', {
upgrade: false,
transports: ['websocket']
})
Weirdly, just setting the transports property to an array with websockets only wasn't enough; I also had to disable upgrade. Is this correct?
Update
I made some new discoveries.
With transports set to ['websocket'] only, it doesn't make any difference wether upgrade is enabled or not. Is that normal?
There are two types of "upgrades" happening with socket.io. First (in socket.io 1.0+), socket.io starts all connections with an http polling request and it may actually exchange some initial data with just an http request. Then, at some point after that, it will try to actually initiate a webSocket connection. the webSocket connection is done by sending a particular type of http request that specifies an upgrade: websocket header and the server can then respond appropriately whether it supports websocket or not. If the server agrees to the upgrade, then that particular http connection is "upgraded" to the webSocket protocol. At that point, the client then knows that webSocket is supported and it stops using the polling http requests, thus completing its upgrade to webSocket.
You can prevent the initial http polling entirely by doing this on the client:
var socket = io({transports: ['websocket'], upgrade: false});
This will prevent polling connections from your own cooperating clients. If you want to prevent any clients from ever using polling, then you can add this to the server:
io.set('transports', ['websocket']);
But, if you set this on the server, socket.io clients that are initially connecting with http polling will not work at all. So, this should only be matched with the right settings in the client such that the client never starts with polling.
This will tell both ends that you only want to use webSockets and socket.io will skip the extra http polling at the beginning. Fair warning, doing this requires webSocket support so this rules out compatible with older versions of IE that didn't yet support webSocket. If you want to retain compatibility, then just let socket.io do it's thing with a couple http requests initially.
Here's more info on the protocol upgrade from http to webSocket.
The webSockets protocol initiates EVERY webSocket with an HTTP connection. That's the way all webSockets work. That HTTP connection contains some headers on it that indicate that the browser would "like" to upgrade to the webSockets protocol. If the server support that protocol, then it responds telling the client that it will upgrade to the webSocket protocol and that very socket then switches from the HTTP protocol to the webSocket protocol. This is how a webSocket connection is designed to work. So, the fact that you see your webSocket connection starting with an HTTP connection is 100% normal.
You can configure socket.io to NEVER use long polling if that makes you feel better, but this will not change the fact that the webSocket connection will still start with an HTTP connection that is then upgraded to the webSocket protocol and it will not improve the efficiency of operation in modern browsers that support webSockets. It will, however make it so that your connection will not work in older browsers.
To tell Socket.IO to use WebSocket only instead of a few XHR requests first, just add this to the Node server:
io.set('transports', ['websocket']);
And on the client add this:
var socket = io({transports: ['websocket']});
This tells Socket.IO to only use WebSocket protocol and nothing else; it's cleaner, faster and uses a little less resources on the client and server sides.
Now you'll only see a single WebSocket connection in your network request list, just keep in mind IE9 and earlier can't use WebSocket.
I'm posting that answer because the accepted answer is not correct - it confuses the Socket.IO upgrade from long-polling AJAX to WebSocket with the WSS protocol "Connection: Upgrade" request. The issue is not that the WebSocket connection starts as HTTP and gets upgraded to WebSocket - how could it not? - but that Socket.IO starts with a long-polling AJAX connection even on browsers supporting WebSocket, and only upgrades it later after exchanging some traffic. It's very easy to see in the developer tools of Firefox or Chrome.
The author of the question is correct in his observations.
The "upgrade" in Socket.IO doesn't refer to the HTTP to WSS protocol upgrade as is often misunderstood but to the upgrade of Socket.IO connection from long-polling AJAX connection to WebSocket. If you start with WebSocket already (which is not the default) then upgrade false has no effect because you don't need to upgrade. If you start with polling and disable upgrade then it stays that way and doesn't upgrade to WebSocket.
See answers by arnold and Nick Steele if you want to avoid starting with long-polling. I will explain what is going on in more detail.
This is what I observed in my experiments with simple WebSocket and Socket.IO apps:
WebSocket
2 requests, 1.50 KB, 0.05 s
From those 2 requests:
HTML page itself
connection upgrade to WebSocket
(The connection upgrade request is visible on the developer tools with a 101 Switching Protocols response.)
Socket.IO
6 requests, 181.56 KB, 0.25 s
From those 6 requests:
the HTML page itself
Socket.IO's JavaScript (180 kilobytes)
first long polling AJAX request
second long polling AJAX request
third long polling AJAX request
connection upgrade to WebSocket
Details
WebSocket results that I got on localhost:
Socket.IO results that I got on localhost:
Test yourself
I published the code on npm and on GitHub, you can run it yourself:
# Install:
npm i -g websocket-vs-socket.io
# Run the server:
websocket-vs-socket.io
and follow instrictions. To uninstall:
# Uninstall:
npm rm -g websocket-vs-socket.io
See this answer for more info.
I thought I should add to the accepted answer above, as if anyone wants to eliminate the XHR Polling transport and initiate websockets right away. The code below is just to give an idea of the implementation:
var url = serverUrl + "/ssClients" //ssClients is the socket.io namespace
var connectionOptions = {
"force new connection" : true,
"reconnection": true,
"reconnectionDelay": 2000, //starts with 2 secs delay, then 4, 6, 8, until 60 where it stays forever until it reconnects
"reconnectionDelayMax" : 60000, //1 minute maximum delay between connections
"reconnectionAttempts": "Infinity", //to prevent dead clients, having the user to having to manually reconnect after a server restart.
"timeout" : 10000, //before connect_error and connect_timeout are emitted.
"transports" : ["websocket"] //forces the transport to be only websocket. Server needs to be setup as well/
}
var socket = require("socket.io-client")(url, connectionOptions);
socket.on("connect", function (_socket) {
logger.info("Client connected to server: " + clientName);
logger.info("Transport being used: " + socket.io.engine.transport.name);
socket.emit("join", clientName, function(_socketId) { //tell the server the client name
logger.info("Client received acknowledgement from server: " + _socketId);
logger.info("Transport being used after acknowledgement: " + socket.io.engine.transport.name);
});
});
After the server is setup, you will see this:
2015-10-23T19:04:30.076Z - info: Client connected to server: someClientId
2015-10-23T19:04:30.077Z - info: Transport being used: websocket
2015-10-23T19:04:30.081Z - info: Client received acknowledgement from server: aMH0SmW8CbiL8w5RAAAA
2015-10-23T19:04:30.081Z - info: Transport being used after acknowledgement: websocket
If you don't force the transport, you'd see "polling" instead of websocket. However, this doesn't happen on the client side alone, the server must be setup as well:
var io = require("socket.io")(server, { adapter: adapter, log: false }); //attach io to existing Express (http) server
..
io.set('transports', ['websocket']); //forces client to connect as websockets. If client tries xhr polling, it won't connect.
Danger
If the client actually does not support the websocket protocol, a connection won't happen and the client will report an xhr poll error.
This is working perfectly for me because I can control the clients I have, so I have the luxury to force websockets right away, which I believe is what the original question is asking. I hope this helps someone out there...

Client-side socket.io without a node.js server

To use socket.io on the client side, usually we start a node.js server and go like this:
<script src="/socket.io/socket.io.js"></script>
or with specific port:
<script src="http://localhost:3700/socket.io/socket.io.js"></script>
Question is:
is it necessary to use node.js server to serve socket.io.js ?
...or is it possible to
make a local copy of socket.io.js instead of goes to server every single time we need socket.io?
like, we go to view source and copy everything we got from the source of script tag,
paste and save it as socket.io-local.js so that next time we use:
<script src="socket.io-local.js"></script>
will that work ?
Updates
Thanks for everyone's great response,
I'm asking this because in the case I'm involved, I don't actually have access to the server:
I am writing the client-side to connect to other developer's Socket Sever which is written in Java.
Therefore I'll have to think a way to work around the fact that I don't have a server there for me.
from what I've been testing,
this way seems to work but I really don't know what's happening behind the scene.
You obviously can host the socket.io client library anywhere and pull it in to a page. However, it will almost certainly not work with your Java-based server.
To understand why, you need to understand what socket.io is really doing behind the scenes; the client library is only a small part of it.
Socket.io actually defines and implements its own protocol for realtime communication between a browser and a server. It does so in a way that supports multiple transports: if—for example—a user's browser or proxy doesn't support WebSockets, it can fall back to long polling.
What the socket.io client actually does is:
Makes a XHR GET request for /socket.io/1. The server responds with a session ID, configured timeouts, and supported transports.
The client chooses the best transport that the user browser supports. In modern browsers, it will use WebSockets.
If WebSockets are supported, it creates a new WebSocket to initiate a WebSocket connection (HTTP GET with Upgrade: websocket header) to a special URL – /socket.io/1/websocket/<session id>.
If WebSockets aren't supported by the browser or fail to connect (there are lots of intermediaries in the wild like proxies, filters, network security devices, and so forth that don't support WebSocket requests), the library falls back to XHR long polling, and makes a XHR request to /socket.io/1/xhr-polling/<sesion id>. The server does not respond to the request until a new message is available or a timeout is reached, at which point the client repeats the XHR request.
Socket.io's server component handles the other end of that mess. It handles all the URLs under /socket.io/, setting up sessions, parsing WebSocket upgrades, actually sending messages, and a bunch of other bookkeeping.
Without all of the services provided by the socket.io server, the client library is pretty useless. It will just make a XHR request to a URL that doesn't exist on your server.
My guess is that your Java-based server just implements the WebSockets protocol. You can connect directly to it using the browser-provided WebSocket APIs.
It is possible that your server does implement the socket.io protocol – there are a few abandoned Java projects to do that – but that's unlikely. Talk with the developer of your server to find out exactly how he's implemented a "socket server."
A standalone build of socket.io-client is exposed automatically by the socket.io server as /socket.io/socket.io.js. Alternatively you can serve the file socket.io-client.js found at the root of this repository.
https://github.com/LearnBoost/socket.io-client
I have a module called shotgun-client that actually wraps socket.io. I needed to serve a custom client script as well as the socket.io client script, but I didn't want every user of my module to have to include multiple script references on their pages.
I found that, when installed, you can serve the generated client script from socket.io by reading the file /node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js. So my module adds a listener for its own URL and when it serves my custom client script it also serves the socket.io client script with it. Viola! Only a single script reference for the users of my module :)
While this is technically possible, I don't see why you'd need to do that. If you're concerned about reducing the data that goes over the wire, this change won't actually do much beyond the few characters saved in the shorter src tag. Simply changing the location of the JS file on the server won't actually improve performance - the JS has to be sent.
Proper caching (which Socket.IO has) will return a 304 Not Modified (and not re-send the JS file every time you load a page).

node.js and socket.io. transport type configuration for websocket?

This question concerns socket.io versions < 0.9.x.
Newer versions have different transports and methods of setting transports.
I test node js and socket.io in two week. when I began I get the problem from socket.send(message) function in client. I can't send any message to the server. But I still can receive messages from the server. I solved this problem when I found the configure transport of server side:
socket.set('transports',[
'xhr-polling'
, 'jsonp-polling'
]);
Everything good. Now I can send messages to the server as well. But I still have a question why I have to configure transport. Default socket.io use websocket transport setting like this:
socket.set('transports', [
'websocket'
, 'flashsocket'
, 'htmlfile'
, 'xhr-polling'
, 'jsonp-polling'
]);
so it uses websocket at first, not xhr-polling. But the server cannot receive any messages sent from the client when using socket.send(msg) even socket.emit(...).
So the problem is: what is not supporting websocket here? browser or node.js ... I'm sorry but I searched so many pages from google and I haven't found an answer for this.
I use node.js version 0.8.16, socket.io version 0.9.13 and newest browsers: chrome, firefox, opera
I want to use websocket not xhr-polling.
That's odd because even if websockets are not supported by your server configuration, socket.io will select the next best available method (in your case xhr-polling). Actually, you shouldn't even need to set those transports as socket.io will try to use 'websocket' as a primary method by default. This may indicate some other problem, possibly with your code?
What is not supporting websockets is definitely not the browsers you're using nor node.js of course. This will depend on your server setup.
First check:
The port you're listening to is open in your firewall
Your webserver supports websockets. If you're using Apache and proxing your request to an internal IP:PORT, websocket will not work unless you install something like apache-websocket or pywebsocket
What finally solved my issue was to disable Apache listening on port 80 and having node.js listening on that port. Here's the answer on SO that helped me: https://stackoverflow.com/a/7640966/2347777

Categories