Is it possible to use Socket.IO in a cross domain manner? If so, how? The possibility is mentioned around the web but no code examples are given anywhere.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Simply insert your remote domain name when creating the client side socket:
Socket.io supports cross-domain connections, but keep in mind that your cookie will not be passed to the server. You'll have to either:
(1) come up with an alternate identification scheme (a custom token or a javascript cookie-- just keep in mind this should not be the actually session id, unless you want to put yourself at risk of session hijacking)
or (2) send a good old fashioned HTTP JSONP request to the server first to get the cookie. Then it will be transmitted w/ the socket connection handshake.
Yes it does. I have implemented cross domain socket.io to test whether it works.
That should work fine.
Quoting the socket.io FAQ:
As to how it does it: Native WebSockets are cross-domain by design, socket.io serves a flash policy file for cross-domain flash communication, XHR2 can use CORS, and finally you can always use JSONP.
**Socket.IO version --> 1.3.7 **
Is it possible to use Socket.Io in a cross domain manner? Yes, absolutely.
If so, how?
Option 1: Force use of Websockets only
By default, websockets are cross domain. If you force Socket.io to only use that as means to connect client and server, you are good to go.
Server side
Client side
That's it. Problem? Won't work on browsers (for clients) who don't support websockets. With this you pretty much kill the magic that is Socket.io, since it gradually starts off with long polling to later upgrade to websockets (if client supports it.)
If you are 100% sure all your clients will access with HTML5 compliant browsers, then you are good to go.
Option 2: Allow CORS on server side, let Socket.io handle whether to use websockets or long polling.
For this case, you only need to adjust server side setup. The client connection is same as always.
Server side
That's it. Hope it helps anyone else.
Easy and security!
In the main file place it before io.on('connection'), add the lines: