Socket.IO中的跨域连接

发布于 2024-12-28 11:30:31 字数 61 浏览 5 评论 0原文

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

风向决定发型 2025-01-04 11:30:31

引用 socket.io 常见问题解答

Socket.IO支持跨域连接吗?

当然,在每个浏览器上!

至于它是如何做到的:本机 WebSocket 在设计上是跨域的,socket.io 为跨域闪存通信提供闪存策略文件,XHR2 可以使用 CORS,最后您始终可以使用 JSONP。

Quoting the socket.io FAQ:

Does Socket.IO support cross-domain connections?

Absolutely, on every browser!

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.

疯了 2025-01-04 11:30:31

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

是否可以跨域方式使用Socket.Io?
是的,绝对是。

如果是,如何实现?

选项 1:仅强制使用 Websocket

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

服务器端

//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' ]);

客户端

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

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

如果你 100% 确定所有客户端都将使用 HTML5 兼容的浏览器进行访问,那么你就可以走了。

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

对于这种情况,您只需调整服务器端设置即可。客户端连接与往常相同。

服务器端

//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();
 });

就是这样。希望它对其他人有帮助。

**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

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

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

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

夜吻♂芭芘 2025-01-04 11:30:31

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

const socket = new WebSocket('ws://example.com/echo');

一些 MDN 上的文档

但是,您应该确保您的服务器接受 Websocket(配置和标头)。


旧版本:

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

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

const socket = new WebSocket('ws://example.com/echo');

Some documentation on MDN

You should however ensure that your server accepts websockets (configuration and headers).


Old version :

var socket = io.connect('http://example.com:8080');
落叶缤纷 2025-01-04 11:30:31

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

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

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

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.

只有影子陪我不离不弃 2025-01-04 11:30:31

通过 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')});

在 origins 数组中指定有效的 origin

create your server by io like this:

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

偏爱你一生 2025-01-04 11:30:31

简单又安全!

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

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

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

Easy and security!

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

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

io.on('connection', function (socket) {
苏璃陌 2025-01-04 11:30:31

是的,确实如此。
我实现了跨域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>

那应该可以正常工作。

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

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

甜妞爱困 2025-01-04 11:30:31

从 v4 开始,根据 文档

从 Socket.IO v3 开始,您需要显式启用 Cross-源资源共享 (CORS)。

您可以在传递给 new Server() 的配置对象中使用 cors 键。请参阅上述文档页面中的基本示例

import { createServer } from "http";
import { Server } from "socket.io";

const httpServer = createServer();
const io = new Server(httpServer, {
  cors: {
    origin: "https://example.com"
  }
});

origin 可以是接受多个来源的数组。

其他选项包括 allowRequestallowedHeaderswithCredentialsextraHeaders 以及 cors中的其他内容最终在后台处理 CORS 标头。

我还测试了与 这个答案 稍有不同的语法,它适用于 4.4.1:

const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io")(server, {
  cors: {origin: ["https://glitch.me", "https://cdpn.io"]}
});

As of v4, according to the docs:

Since Socket.IO v3, you need to explicitly enable Cross-Origin Resource Sharing (CORS).

You can use the cors key in the configuration object passed to new Server(). See this basic example from the above docs page:

import { createServer } from "http";
import { Server } from "socket.io";

const httpServer = createServer();
const io = new Server(httpServer, {
  cors: {
    origin: "https://example.com"
  }
});

origin can be an array to accept multiple origins.

Other options include allowRequest, allowedHeaders, withCredentials, extraHeaders and others from the cors package which ultimately handles the CORS headers under the hood.

I also tested slightly different syntax than this answer, which worked for me with 4.4.1:

const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io")(server, {
  cors: {origin: ["https://glitch.me", "https://cdpn.io"]}
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文