使用socket.io提供静态文件的问题

时间:2013-12-17 21:50:49

标签: jquery node.js express socket.io

我正在创建一个用户可以登录的Web应用程序(pwd / username)。登录后,他可以选择2个可用应用程序中的一个。 第一个应用程序,使用客户端和服务器之间的http连接。 第二个使用Web套接字。因此,当用户点击第二个应用程序时,应该建立一个websocket。 我的第一个应用程序工作正常,也是第二个应用程序,但是当我把所有的应用程我有一个问题。

这是我到目前为止所做的:

server.js

var app = express();
var server = http.createServer(app, function(req, res) {
  //serves static files
  //processes GET and POST requests of both the login page and the 1st app 
}

server.listen(80, function() {
   console.log("Server listening on port 80.");
}); 

app.configure(function () {
    app.use(express.cookieParser());
    app.use(express.session({secret: 'secret', key: 'express.sid'}));
});

 app.get('/', function (req, res) {
   var filePath = '../client/index.html';
   if (filePath){
      var absPath = './' + filePath;
      serveStatic(res, cache, absPath); //function that serves static files
   } 
}); 
io = io.listen(server);
io.set('authorization', function (handshakeData, accept) {
  //code
});

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

的index.html

    <script src="../third-party/jquery-1.9.1.min.js"></script>
    <script src="/socket.io/socket.io.js"></script>

<script>
    $(document).ready(function() {

    tick = io.connect();
          tick.on('data', function (data) {
              console.log(data);
          });

          tick.on('error', function (reason){
            console.error('Unable to connect Socket.IO', reason);
          });

          tick.on('connect', function (){
            console.info('successfully established a working and authorized connection');
          });
    });
</script>

在客户端,我使用jquery。

当我连接到我的localhost时,我得到了登录页面,并在chrome调试工具上显示一条错误消息:$ is undefined(在index.html中),GET http://localhost/third-party/jquery-1.9.1.min.js 404 (Not Found)

以下是我的应用的架构:

- server
   - server.js
-client
     -index.html (login page)
     -firstApp 
       -index.html
     -secondApp (uses websocket)   
         -index.html
     - third-party
         -jquery-1.9.1.min.js

我相信,我不是以正确的方式提供静态文件。虽然在将websocket添加到我的代码之前,我没有遇到任何问题。 我不明白的是当我在

下记录某些内容时
var server = http.createServer(app, function(req, res) {
   console.log('TEST')
});

控制台上没有显示任何内容。 以下是为静态文件提供服务的函数:

function sendFile(res, filePath, fileContents) {
   res.writeHead(200, {"content-type": mime.lookup(path.basename(filePath))});
   res.end(fileContents);
} 

function serveStatic(res, cache, absPath) {
   //checks if file is cached in memory
   if (cache[absPath]) {
      sendFile(res, absPath, cache[absPath]); //serves file from memory
   }else {
      fs.exists(absPath, function(exists) { //checks if file exists
         if (exists) { 
            fs.readFile(absPath, function(err, data) { //reads file from disk
               if (err) {
               }else {
                  cache[absPath] = data;
                  sendFile(res, absPath, data); //serves file from disk
               }
            });
         }else {
            console.log('cannot find the file')
            send404(res);
         }
      });
   }
} 

1 个答案:

答案 0 :(得分:2)

只需添加

即可

app.use( express.static(__dirname+'../client') );

到您的中间件链,并从index.html相对于客户端目录请求文件,如下所示:

<强> secondApp / index.html中

<script src="/third-party/jquery-1.9.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>

express.static是对connect.static

的引用

恕我直言,请至少清理你的server.js代码

var app = express()
  , server = http.createServer(app)
  , io = io.listen(server)
;

app.configure(function () {
    app.use( express.cookieParser() );
    app.use( express.session({secret: 'secret', key: 'express.sid'}) );
    app.use( app.router )
    app.use( express.static(__dirname+'../client') );
});


app.get('/', function (req, res) {
    res.sendFile( __dirname+'../client/index.html' ) 
});

app.get('/whatever/url/path/you/want', function (req, res) {
    // this will match GET requests to /whatever/url/path/you/want
});

app.get('*', function (req, res) {
    // this will match GET requests to any path
    // take care if you use middlewares after app.router as here
});

app.post('/whatever/url/path/you/want', function (req, res) {
    // this will match POST requests to /whatever/url/path/you/want
});

app.post('*', function (req, res) {
    // this will match POST requests to any path
});

io.set('authorization', function (handshakeData, accept) {
});

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

server.listen(80, function() {
   console.log("Server listening on port 80.");
});

警告:以上不是最干净的最好的代码

查看http.createServer documentation

它只接受1个侦听器进行resquest。您可以注册2个侦听器,但由于您使用express,最好的方法是使用它的功能,请参阅上面的示例在server.js示例代码

您不需要提及的serveStatic功能

express.static对您来说已经足够了。

旁注

您无需在客户端io.connect下包装$.ready