我正在使用socket.io设置聊天服务器。我一直遵循他们的教程,直到涉及到SSL。我在网络上的堆栈和教程中找到了一些说明,因此我想出了以下代码。
我用“ my-domain.de”替换了我的真实域名
var app = require('express')();
var fs = require('fs');
var https = require('https');
var io = require('socket.io')(https);
var mysql = require('mysql');
var options = {
key: fs.readFileSync('/etc/letsencrypt/live/my-domain.de/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/my-domain.de/cert.pem'),
ca: fs.readFileSync('/etc/letsencrypt/live/my-domain.de/chain.pem')
};
var serverPort = 8443;
var server = https.createServer(options, app);
server.listen(serverPort, function(){
console.log('listening on *:' + serverPort);
});
io.on('connection', function(socket){
console.log('a user connected');
});
服务器运行,但是客户端未收到socket.io.js。因此,我使用DEBUG = * -node index.js启动了服务器,以查看发生了什么。当客户端尝试连接时,它显示以下错误:
express:application no routes defined on app +9s
finalhandler default 404 +0ms
客户端如下:
<script src="https://my-domain.de:8443/socket.io/socket.io.js"></script>
<script>
$(function () {
var socket = io('https://my-domain.de:8443/');
</script>
答案 0 :(得分:0)
头痛几小时后,我找到了解决方法,它和以往一样简单...
我只需要将var io = require('socket.io')(server);
放在var server = https.createServer(options, app);
之后,以便它可以正确路由...
这样我的最终服务器代码如下:
var app = require('express')();
var fs = require('fs');
var https = require('https');
var mysql = require('mysql');
var options = {
key: fs.readFileSync('/etc/letsencrypt/live/my-domain.de/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/my-domain.de/cert.pem'),
ca: fs.readFileSync('/etc/letsencrypt/live/my-domain.de/chain.pem')
};
var serverPort = 8443;
var server = https.createServer(options, app);
var io = require('socket.io')(server); // HERE TO PUT THE DAMN SOCKET.IO!!
server.listen(serverPort, function(){
console.log('listening on *:' + serverPort);
});
io.on('connection', function(socket){
console.log('a user connected');
});