简体   繁体   English

node.js:socket.io与express.static

[英]node.js: socket.io vs express.static

I have the following server.js running: 我正在运行以下server.js:

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. 简单的express.static服务器,用于/ public子文件夹中的文件,以及socket.io功能。 With this setup, any request for the 'socket.io.js' file fails, ie 使用此设置,对“ socket.io.js”文件的任何请求都会失败,即

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

returns a 404 error (file not found). 返回404错误(找不到文件)。 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. 如果我只是使用“ http”模块而不是“ express”(注释express.static和express.logger行),则将正确提供socket.io.js。 How can I combine both functionalities? 如何结合这两种功能?

Express 3.0.0 (lastest) change its API. Express 3.0.0(最新)更改其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);

Make sure you have the last versions of express.js and of socket.io.js. 确保您拥有Express.js和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); 否则,一个解决方案是调用var io = require('socket.io').listen(server); after your server.use server.use

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM