Socket.io (www.socket.io) is POWERFULL and one of the most famous and professional library to real time communication. Socket.IO enables real-time bidirectional event-based communication.
It works on every platform, browser or device, focusing equally on reliability and speed. Most well-known usage this library:
- Real-time analytics – Push data to clients that gets represented as real-time counters, charts or logs.
- Binary streaming – Starting in 1.0, it’s possible to send any blob back and forth: image, audio, video.
- Instant messaging and chat – Socket.IO’s “Hello world” is a chat app in just a few lines of code.
- Document collaboration – Allow users to concurrently edit a document and see each other’s changes.
Many samples presented on blogs, books, documentations concerns application socket.io in case of client and server implementation on the same domain, server. But what about situation when the client frontend site is located in another domain (e.g. www.domain-client.com) and another physical machine and rest api on another one (e.g. www.domain-api.com).
Is it possible to use socket.io in this situation e.g. on microsoft azure or another cloud solution? If You will try implement solution based on samples from many books, blogs where described is solution where socket.io works on the same physical machine and domain – then You will fall down. After running your sample You will see a lot of errors on the client side in browser like following:
“XMLHttpRequest cannot load http://domain-api.com/socket.io/?EIO=2&transport=polling&sid=z1N_9JpKElJJ6b2qAAAL. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://domain-client.com’ is therefore not allowed access.”
If You place this error in google You will find a lot of articles where people try solve this issue without success.. 99% of people say that problem is in configuration of headers in express (or another distributions of node.js ), and they try set up configuraiton for headers on node.js server side.. 1% is closest to solution becouse focus on response headers from socket.io.. But no one one solution works.. problem is the same. The another people try to use on client side url adrdress to socket.io library located on server e.g.
But solution is very easy. I will demonstrate sample based on express.js distribution:
By default, websockets are cross domain. You have to force Socket.io to only use that as means to connect client and server by source code line:
Please pay attention on snippet of code – IT IS MOST IMPORTANT part for start works our solution:
The last information: You don’t have to use socket.io lib from destination server e.g.
And here we go ahead.. See You to the next post