NodeJS无法连接套接字

时间:2018-07-02 10:04:36

标签: node.js express socket.io raspbian

因此,我是Node.js的新手,并学习了一些教程。由于本教程仅使用https,因此我试图与Https建立基本的套接字连接。

var express = require('express');
var app = express();
var fs = require('fs');
var https = require('https');
var privateKey  = fs.readFileSync(__dirname+'/key.pem', 'utf8');
var certificate = fs.readFileSync(__dirname+'/server.crt', 'utf8');

var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();

// your express configuration here
var serv = https.createServer(credentials, app);

app.get('/',function(req, res){
    res.sendFile(__dirname+'/client/index.html');
});
app.use ('/client',express.static(__dirname+'/client'));
serv.listen(8080);
console.log('server started');

var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){
    console.log('socket connection');
});

我从没在控制台上看到套接字连接。

这是HTML

hello world
<script src="https://cnd.socket.io/socket.io-1.4.5.js"></script>
<script>
    var socket = io();
</script>

你知道我在做什么错吗? Socket.io是否支持https?

1 个答案:

答案 0 :(得分:0)

第一件事,如果您有快递的话,就不需要https创建服务器。

这是您可以做的:

var express = require('express');  
var app = express();  
var server = require('http').createServer(app);  
var io = require('socket.io')(server);

io.sockets.on('connection', function(socket){
    console.log('socket connection');
});

如果运行此代码,将在控制台上打印socket connection