对于socket.io同时使用http和https [英] Use both http and https for socket.io

查看:460
本文介绍了对于socket.io同时使用http和https的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 http https 连接的socket.io工作,但是似乎与我的配置只能在其中一个上。



使用下面的配置选项,socket.io可以通过 https ,但是当尝试通过常规 http 访问时,它无法连接,我收到错误。

  var app = express()
,http = require('http')。createServer(app)
,https = require('https')。 )
,io = require('socket.io')。listen(https,{log:false})

然后我有这个

  http.listen(80,serverAddress); 
https.listen(443,serverAddress);

在客户端我有:

 < script src ='/ socket.io/socket.io.js'></script> 

var socket = io.connect('https://<%= serverAddress%>',{secure:true,'sync disconnect on unload':true});

当然,如果我使用 .listen上的https选项切换http .connect 服务器和客户端的功能分别我有相反的结果。 Socket.io可以通过http访问,而不是通过https访问。



如何实现这一点?我需要它主要是因为它是一个Facebook应用程序,所以它必须提供http和https连接选项根据Facebook规则。



编辑:如果它有助于问题,我收到的错误是以下

 无法加载资源:服务器回复状态为404(未找到)http://DOMAIN/socket.io/socket.io.js 

因为这个我得到别人如:

 未捕获ReferenceError:未定义io 


解决方案

我相信问题在于您在服务器端设置socket.io的方式在客户端上。



这是我如何工作(只为你)。



服务器:

  var debug = require('debug')('httpssetuid'); 
var app = require('../ app');
var http = require('http');
var https = require('https');
var fs = require('fs');
var exec = require('child_process')。exec;
var EventEmitter = require('events')。EventEmitter;
var ioServer = require('socket.io');

var startupItems = [];
startupItems.httpServerReady = false;
startupItems.httpsServerReady = false;

var ee = new EventEmitter();

ee.on('ready',function(arg){
startupItems [arg] = true;
if(startupItems.httpServerReady&&& startupItems.httpsServerReady){
var id = exec('id -u'+ process.env.SUDO_UID,function(error,stdout,stderr){
if(error || stderr)throw new Error(error || stderr) ;
var uid = parseInt(stdout);
process.setuid(uid);
console.log('de-escalated privileges。now running as%d',uid);
setInterval(function cb(){
var rnd = Math.random();
console.log('emit update:%d',rnd);
io.emit('更新',rnd);
},5000);
});
};
});

app.set('http_port',process.env.PORT || 80);
app.set('https_port',process.env.HTTPS_PORT || 443);

var httpServer = http.createServer(app);

var opts = {
pfx:fs.readFileSync('httpssetuid.pfx')
};
var httpsServer = https.createServer(opts,app);

var io = new ioServer();

httpServer.listen(app.get('http_port'),function(){
console.log('httpServer listen on port%d',app.get('http_port') );
ee.emit('ready','httpServerReady');
});

httpsServer.listen(app.get('https_port'),function(){
console.log('httpsServer listen on port%d',app.get('https_port') );
ee.emit('ready','httpsServerReady');
});

io.attach(httpServer);
io.attach(httpsServer);

io.on('connection',function(socket){
console.log('socket connected:%s',socket.id);
});

客户:




脚本(src ='/ socket.io/socket.io.js')
脚本。
var socket = io();
socket.on('update',function(update){
document.getElementById('update')。innerHTML = update;
});

以下是服务器的要点:


  1. 需要socket.io但是不要调用它的listen方法(假设已经需要http和https)。相反,只是保持参考。 (var ioServer = require('socket.io'))

  2. 创建你的http& https服务器

  3. 创建ioServer的新实例

  4. 绑定您的http和https服务器(.listen)

  5. 将http& https服务器实例附加到io实例。 (.listen是.attach的别名)

  6. 设置io事件

客户端(翡翠语法,但你得到的想法):


  1. include socket.io脚本标记

  2. <调用io并捕获参考
  3. 设置您的事件处理程序

在客户端上,需要调用io.connect()。此外,我不知道你在那里的选择。看起来你有一个打字错误(,,),我找不到任何安全的参考:在1.0文档中为true。


I am trying to make socket.io work both on http and https connections, but it seems that with my configuration it can work only on one of them.

With the below config options socket.io can access my application through https, but when trying to access through regular http it cannot connect and i receive errors.

    var app = express()
  , http= require('http').createServer(app)
  , https = require('https').createServer(options, app)
  , io = require('socket.io').listen(https, { log: false })

And later i have this

http.listen(80, serverAddress);
https.listen(443, serverAddress);

On client side i have this:

<script src='/socket.io/socket.io.js'></script>

var socket = io.connect('https://<%= serverAddress %>', {secure: true, 'sync disconnect on unload' : true});

Of course if i switch the http with the https options on the .listen and .connect functions of the server and the client respectively i am having the reverse results. Socket.io can access through http and not through https.

How is it possible to achieve this? I need it mostly because it is about a facebook app, so it must provide both http and https connection options according to facebook rules.

Edit: In case it helps about the problem, the error i am receiving is the below

Failed to load resource: the server responded with a status of 404 (Not Found) http://DOMAIN/socket.io/socket.io.js

And because of this i get others such as:

Uncaught ReferenceError: io is not defined 

解决方案

I believe the problem is in your way of setting up socket.io on the server side and on the client.

Here's how I made it work (just for you).

Server:

var debug = require('debug')('httpssetuid');
var app = require('../app');
var http = require('http');
var https = require('https');
var fs = require('fs');
var exec = require('child_process').exec;
var EventEmitter = require('events').EventEmitter;
var ioServer = require('socket.io');

var startupItems = [];
startupItems.httpServerReady = false;
startupItems.httpsServerReady = false;

var ee = new EventEmitter();

ee.on('ready', function(arg) {
  startupItems[arg] = true;
  if (startupItems.httpServerReady && startupItems.httpsServerReady) {
    var id = exec('id -u ' + process.env.SUDO_UID, function(error, stdout, stderr) {
      if(error || stderr) throw new Error(error || stderr);
      var uid = parseInt(stdout);
      process.setuid(uid);
      console.log('de-escalated privileges. now running as %d', uid);
      setInterval(function cb(){
        var rnd = Math.random();
        console.log('emitting update: %d', rnd);
        io.emit('update', rnd);
      }, 5000);
    });
  };
});

app.set('http_port', process.env.PORT || 80);
app.set('https_port', process.env.HTTPS_PORT || 443);

var httpServer = http.createServer(app);

var opts = {
  pfx: fs.readFileSync('httpssetuid.pfx')
};
var httpsServer = https.createServer(opts, app);

var io = new ioServer();

httpServer.listen(app.get('http_port'), function(){
  console.log('httpServer listening on port %d', app.get('http_port'));
  ee.emit('ready', 'httpServerReady');
});

httpsServer.listen(app.get('https_port'), function(){
  console.log('httpsServer listening on port %d', app.get('https_port'));
  ee.emit('ready', 'httpsServerReady');
});

io.attach(httpServer);
io.attach(httpsServer);

io.on('connection', function(socket){
  console.log('socket connected: %s', socket.id);
});

Client:

script(src='/socket.io/socket.io.js')
script.
  var socket = io();
  socket.on('update', function(update){
    document.getElementById('update').innerHTML = update;
  });

Here are the key points for the server:

  1. require socket.io but don't call it's listen method yet (assuming http and https are already required). Instead, just keep the reference. (var ioServer = require('socket.io'))
  2. create your http & https server
  3. create a new instance of ioServer
  4. bind your http and https servers (.listen)
  5. attach http&https server instances to the io instance. (.listen is an alias for .attach)
  6. setup io events.

And the client (jade syntax but you get the idea):

  1. include socket.io script tag
  2. call io and capture reference
  3. setup your event handlers

On the client you don't need to call io.connect(). Furthermore, I'm not sure about your options there. It looks like you have a typo (, ,) and I can't find any reference to secure: true in the 1.0 documentation.

这篇关于对于socket.io同时使用http和https的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆