我使用简单的socket.io 2.0.3服务器,没有快速或类似的东西,在我的Laravel应用程序中运行简单的聊天功能。
在我决定将网站切换到HTTPS之前,一切运行良好。现在socket.io拒绝连接(ERR_CONNECTION_CLOSED)。
这是我最简单的设置:
server.js:
var io = require('socket.io')(8080, {
origins : //some stuff
});
HTML文件
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
var socket = io(':8080');
//more stuff
我在服务器文件夹,intermediate.crt,domain.com.crt和domain.com.key中都需要证书文件
有人可以通过最简单的示例帮助如何在https上完成这项工作吗?提前谢谢!
编辑:需要可能的解决方案而不使用Express。
答案 0 :(得分:2)
我无法用简单的socket.io代码编写这个,所以我最终使用了express。
如果以后有人需要,这是最简单的工作代码:
<强> server.js 强>
var express = require('express');
var app = module.exports = express();
var https = require('https');
var fs = require('fs');
var server = https.createServer({
key: fs.readFileSync(/*full path to your key*/),
cert: fs.readFileSync(/*full path to your cert*/),
ca: fs.readFileSync(/*full path to your intermediate cert*/),
requestCert: true,
rejectUnauthorized: false
},app);
server.listen(8080); //listen on port 8080
var io = require('socket.io').listen(server);
io.set('origins', /*your desired origins*/);
io.set('transports', ['websocket',
'flashsocket',
'htmlfile',
'xhr-polling',
'jsonp-polling',
'polling']);
var sockets = {};
//your socket logic
HTML中的:
var socket = io(':8080',{secure: true});
答案 1 :(得分:0)
您可以使用所有相关设置创建HTTPS服务器的实例
var https = require('https');
https.createServer(options, app).listen(443);
然后将其传递给构造函数:
new SocketIo(https)
答案 2 :(得分:0)
重要事实:
你必须使用https而不是http, 需要加载crt文件并像示例一样创建选项对象 客户端只需要正确的地址,例如:https://YOUR_domain.com:PORT
服务器端:
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
//High definition
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
// Globals
//var MEMORY_CLEANER_INTERVAL = 5000;
//var crypto = require('crypto');
var tls = require('tls');
//dl = require('delivery');
var fs = require("fs");
var mysql = require('mysql');
var express = require("express");
var app = express();
var http = require('http');
var https = require('https');
//var mkdirp = require('mkdirp');
var path = require('path');
//var nodemailer = require('nodemailer');
//includer
function read(f) {return fs.readFileSync(f).toString();}
function include(f) {eval.apply(global, [read(f)]);}
//var BASE = require('./lib/level1_module');
//BASE.NAME = "YEap";
var pkey = fs.readFileSync('/etc/httpd/ssl/YOUR_FILE.key');
var pcert = fs.readFileSync('/etc/httpd/ssl/YOUR_FILE_com.crt')
var SERVER_PORT = 9000;
var options = {
hostname: 'YOUR_PAGE.com',
port: 9000,
key: pkey,
cert: pcert,
requestCert: true,
rejectUnauthorized: false,
};
var server = https.createServer(options, app).listen(SERVER_PORT, function(){
console.log("Express server listening on port " + SERVER_PORT);
});
var io = require('socket.io').listen(server);
server.listen(SERVER_PORT);
console.log('Socket server listening on port : ' , SERVER_PORT);