使用expressjs解决外部模块中的Socket.io连接问题

时间:2016-03-13 23:02:48

标签: node.js express socket.io webrtc

我有以下情况:当我尝试连接名为' Signaling-Server.js' 在html视图中,控制台说:GET ERROR [HTTP / 1.1 400 Bad Request 1ms] 但这只发生在我添加这些模块时。当我尝试连接时没有他,socket.io连接工作正常。

app.js

let yAxisSpawnLocations: [CGFloat] = [0]
let xAxisSpawnLocations: [CGFloat] = {

    var spawnLocations:[CGFloat] = []   //Create 5 possible spawn locations
    let numberOfNodes = 5

    for i in 0...numberOfNodes - 1 {

        var xPosition = (frame.maxX) / CGFloat((numberOfNodes - 1)) * CGFloat(i)

        xPosition += thePlayer.size.width/2

        xPosition -= frame.maxX/1.6
        spawnLocations.append( xPosition )

    }

    return spawnLocations

}()

信令服务器的代码在这里(MuazKhan Proyect的Cortesy" RTCMultiConnection")

信令-Server.js

//Modules
var express = require("express"),
http = require("http"),
morgan= require("morgan"),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
app = express(),
server = http.createServer(app),
io = require("socket.io").listen(server);

app.use(express.static(__dirname + '/public'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended:false}));
app.use(bodyParser.json());
app.use(methodOverride());

app.set("views",__dirname + "/views");




//I need to 'onnect with this module
//require('./Signaling-Server.js')(myServerOrPort);
require('./Signaling-Server.js')(server);

//Server is ready
server.listen(3000);

有人知道这个问题吗?

2 个答案:

答案 0 :(得分:1)

您可以尝试Ahmed的解决方案,即在此处传递server对象:

require('./Signaling-Server.js') (server);

在您的代码中,server对象正在使用http

我建议尝试这样做:

var fs = require('fs');

var options = {
    key: fs.readFileSync('fake-keys/privatekey.pem'),
    cert: fs.readFileSync('fake-keys/certificate.pem')
};

var express = require("express"),
    http = require("https"), // Use HTTPs here -------------
    app = express(),
    server = http.createServer(options, app);

require('./Signaling-Server.js')(server);

您可以尝试使用有效的SSL证书密钥或fake-keys

以下是如何使用有效证书:

var options = {
    key: fs.readFileSync('../ssl/private/domain.com.key'),
    cert: fs.readFileSync('../ssl/certs/domain.com.crt'),
    ca: fs.readFileSync('../ssl/certs/domain.com.cabundle')
};

答案 1 :(得分:0)

在Express 3中,您应该将app对象传递给socket.io,而不是像Express 2中那样的服务器。假设您使用的是Express 3而不是2.您只需更改一行即可正确设置socket.io < / p>

尝试替换此

require('./Signaling-Server.js')(server);

用这个

require('./Signaling-Server.js')(app);