Javascript Socket.IO中的跨域连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8970880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:15:44  来源:igfitidea点击:

Cross-domain connection in Socket.IO

javascriptwebsocketsocket.iocorscross-domain

提问by CamelCamelCamel

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.

是否可以跨域使用 Socket.IO?如果是这样,如何?网络上提到了这种可能性,但在任何地方都没有给出代码示例。

采纳答案by igorw

Quoting the socket.io FAQ:

引用socket.io 常见问题解答

Does Socket.IO support cross-domain connections?

Absolutely, on every browser!

Socket.IO 是否支持跨域连接?

绝对,在每个浏览器上!

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.

至于它是怎么做的:Native WebSockets 是跨域设计的,socket.io 为跨域 flash 通信提供了一个 flash 策略文件,XHR2 可以使用 CORS,最后你总是可以使用 JSONP。

回答by Chayemor

**Socket.IO version --> 1.3.7 **

**Socket.IO 版本 --> 1.3.7 **

Is it possible to use Socket.Io in a cross domain manner?Yes, absolutely.

是否可以跨域使用 Socket.Io?是的,一点没错。

If so, how?

如果是这样,如何?

Option 1: Force use of Websockets only

选项 1:仅强制使用 Websocket

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.

默认情况下,websockets 是跨域的。如果您强制 Socket.io 仅将其用作连接客户端和服务器的方式,那么您就可以开始了。

Server side

服务器端

//HTTP Server 
var server = require('http').createServer(app).listen(8888);
var io = require('socket.io').listen(server);

//Allow Cross Domain Requests
io.set('transports', [ 'websocket' ]);

Client side

客户端

var connectionOptions =  {
            "force new connection" : true,
            "reconnectionAttempts": "Infinity", //avoid having user reconnect manually in order to prevent dead clients after a server restart
            "timeout" : 10000, //before connect_error and connect_timeout are emitted.
            "transports" : ["websocket"]
        };

 var socket = io("ur-node-server-domain", connectionOptions);

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.)

就是这样。问题?不适用于不支持 websockets 的浏览器(对于客户端)。有了这个,你几乎杀死了 Socket.io 的魔力,因为它逐渐开始长轮询,然后升级到 websockets(如果客户端支持它)。

If you are 100% sure all your clients will access with HTML5 compliant browsers, then you are good to go.

如果您 100% 确定您的所有客户端都将使用符合 HTML5 的浏览器访问,那么您就可以开始了。

Option 2: Allow CORS on server side, let Socket.io handle whether to use websockets or long polling.

选项2:在服务器端允许CORS,让Socket.io处理是使用websockets还是长轮询。

For this case, you only need to adjust server side setup. The client connection is same as always.

对于这种情况,您只需要调整服务器端设置。客户端连接与往常一样。

Server side

服务器端

//HTTP Server 
var express=require('express');
//Express instance
var app = express();

//ENABLE CORS
app.all('/', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
 });

That's it. Hope it helps anyone else.

就是这样。希望它可以帮助其他人。

回答by vinyll

Simply insert your remote domain name when creating the client side socket:

创建客户端套接字时只需插入您的远程域名:

var socket = io.connect('http://example.com:8080');

回答by mikermcneil

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:

Socket.io 支持跨域连接,但请记住,您的 cookie 不会传递到服务器。您必须:

(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 hiHymaning)

(1) 提出一个替代的识别方案(一个自定义令牌或一个 javascript cookie——请记住,这不应该是实际的会话 ID,除非你想让自己面临会话劫持的风险)

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.

或 (2) 首先向服务器发送一个很好的老式 HTTP JSONP 请求以获取 cookie。然后它将通过套接字连接握手进行传输。

回答by mikermcneil

Easy and security!

轻松又安全!

In the main file place it before io.on('connection'), add the lines:

在主文件中将其放在 io.on('connection') 之前,添加以下行:

io.set('origins', 'yoursite.com:*');

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

回答by Kurt Campher

Yes it does. I have implemented cross domain socket.io to test whether it works.

是的,它确实。我已经实现了跨域 socket.io 来测试它是否有效。

<script src="http://your-nodejs-domain.com:3000/public/js/jquery.js"></script>
  <script src="http://your-nodejs-domain.com:3000/socket.io/socket.io.js"></script>
  <script>

      var socket = io.connect('http://your-nodejs-domain:3000');
      $(document).ready(function(){

          socket.on('test message', function(msg){
               console.log("Got the message: " + msg);
          });
      });

  </script>

That should work fine.

那应该可以正常工作。

回答by ghazaleh javaheri

create your server by io like this:

通过 io 创建您的服务器,如下所示:

const server = require('http').createServer();

const io = require('socket.io')(server, {
    origins:["127.0.0.1:8000"],
    path: '/',
    serveClient: false,
    // below are engine.IO options
    pingInterval: 20000,
    pingTimeout: 5000,
    cookie: false
});

io.on('connection', function(socket){
    console.log("here new user welcom")
});


server.listen(3000,function(){
    console.log('listening on *:3000')});

in the origins array specify valid origin

在 origins 数组中指定有效的原点