2011-12-10 107 views
4

我對Node.js和Socket.io很陌生。我已經構建了一個非常基本的Web服務器,但是在使用它時,我無法加載socket.io客戶端文件(我得到一個404)。Node.js - Socket.io客戶端文件沒有被基本節點Web服務器服務

我試圖用這個客戶端代碼:

<script src="/socket.io/socket.io.js"></script> 

我的理解是,節點應該選擇這並解決它?它在一個更簡單的Web服務器示例上執行。

我的web服務器例子,其中尚未解決如下:

var server = http.createServer(function (request, response) { 

    console.log('request starting...'); 

    var filePath = '.' + request.url; 
    if (filePath == './') 
     filePath = './index.html'; 

    var extname = path.extname(filePath); 
    var contentType = 'text/html'; 
    switch (extname) { 
     case '.js': 
      contentType = 'text/javascript'; 
      break; 
     case '.css': 
      contentType = 'text/css'; 
      break; 
    } 

    path.exists(filePath, function(exists) { 

     if (exists) { 
      fs.readFile(filePath, function(error, content) { 
       if (error) { 
        response.writeHead(500); 
        response.end(); 
       } 
       else { 
        response.writeHead(200, { 'Content-Type': contentType }); 
        response.end(content, 'utf-8'); 
       } 
      }); 
     } 
     else { 
      response.writeHead(404); 
      response.end(); 
     } 
    }); 

我如果它確實解決Web服務器的代碼如下:

app.listen(8080); 

function handler (req, res) { 
    fs.readFile(__dirname + '/index.html', 
    function (err, data) { 
    if (err) { 
     res.writeHead(500); 
     return res.end('Error loading index.html'); 
    } 

    res.writeHead(200); 
    res.end(data); 
    }); 
} 

任何人都可以是什麼原因造成建議它不使用第一個Web服務器示例爲客戶端上的socket.io文件提供服務?

最好的問候,本。

+0

哪裏你的socket.io代碼是? – Raynos

回答

11

你可能是一個不同的端口上運行Socket.IO,所以包括以下列格式文件:

服務器:端口/ socket.io/socket.io.js

+0

感謝您的及時回覆。我正在8080上運行Web服務器。請問socket.io不在同一端口上嗎? – Ben

+0

Socket.IO在同一個端口上嗎?你確定? – alessioalex

+0

就是這樣!它在第一個例子中在8080上運行。 非常感謝! 本。 – Ben

相關問題