node.js: socket.io vs express.static

2020-03-13 08:31发布

I have the following server.js running:

module.exports = server;

var express = require('express');
var fs = require('fs');

var server = express.createServer();    

var port = 58000;
server.listen(port);

var io = require('socket.io').listen(server);

server.use(express.static('/', __dirname + '/../public'));

server.use(express.logger());

io.on('connection', function(client){
    console.log('new client connected ' + client);
    client.on('message', function(){
        console.log('client wants something');
    });
});

Simple express.static server for files in a /public subfolder, plus socket.io functionality. With this setup, any request for the 'socket.io.js' file fails, i.e.

http://localhost:58000/socket.io/socket.io.js

returns a 404 error (file not found). Static file server works correctly. If I simply use the 'http' module instead of 'express' (commenting out express.static and express.logger lines) socket.io.js is served correctly. How can I combine both functionalities?

2条回答
Animai°情兽
2楼-- · 2020-03-13 08:50

Make sure you have the last versions of express.js and of socket.io.js. My side it's working great with

express@2.5.8 
socket.io@0.8.5 
node@0.6.5

Otherwise, a solution can be to call var io = require('socket.io').listen(server); after your server.use

查看更多
疯言疯语
3楼-- · 2020-03-13 09:06

Express 3.0.0 (lastest) change its API.

Here is a question very similar to yours that delivers the response.

var express = require('express')
  , http = require('http');

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

...

server.listen(8000);
查看更多
登录 后发表回答