Socket.io配置导致错误404

时间:2017-05-29 21:00:36

标签: node.js http https socket.io

我尝试将socket.io设置到我的节点服务器中,以便为我的应用程序创建消息传递功能,但是尽管测试应用程序正确,但仍然无法正常运行。

server.js:

/* long list of requires */
var express = require('express');
var http = require('http');
var https = require('https');

var config = require('./config');

var app = express();


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


io.on('connection', function(socket){
    console.log('a user connected');
});

/* ssl setup */

// Create an HTTP service.
http.createServer(app).listen(8000); // opens the port
// Create an HTTPS service identical to the HTTP service.
https.createServer(options, app).listen(4433); // for the ssl

的index.html

..bunch of code like bootstrap and angular.js

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.1/socket.io.js"></script>
<script>
    var socket = io.connect('http://localhost:8000');
    socket.on('connect', function(data) {
        socket.emit('join', 'Hello World from client');
    });
</script>

我尝试在localhost:8000上运行该网站。

尽管如此,我在控制台中收到错误404:

  

GET /socket.io/?EIO=3&transport=polling&t=LnM0Fd3 404

我不确定socket.io

的设置过程出了什么问题

1 个答案:

答案 0 :(得分:0)

您正在创建三台服务器,其中只有一台获得Socket.io

// createServer No 1
var server = require('http').createServer(app);
var io = require('socket.io')(server);


// ...

// createServer No 2
http.createServer(app).listen(8000); // opens the port
// Create an HTTPS service identical to the HTTP service.

// createServer No 3
https.createServer(options, app).listen(4433); // for the ssl

你应该只创建一个服务器,并将那个的socket.io调用添加到其中。

如果只创建端口8000服务器,可以像这样添加:

// (exactly your code, except for the "var server = " in front.
var server = http.createServer(app).listen(8000); // opens the port
// the next line is new:
var io = require('socket.io')(server);

请注意,您还必须将io.on......部分移到该行下方。