Node.js - 提供index.html文件以及提供Web套接字

时间:2011-12-11 15:59:12

标签: node.js static web socket.io

我是Node和Socket.io的新手,并试图让下面的代码运行。它旨在为WebSocket请求提供服务,但是我想修改它以提供静态内容,例如index.html。

我的网络套接字代码如下:

var http        = require("http"),
    sys         = require("sys"),
    io          = require("socket.io"),
    GlobTrie    = require("glob-trie.js");

var Brokaw = {};

Brokaw.Server = function(port) {
var self = this;

// setup the basic HTTP server -- socket.io will wrap this
var server  = http.createServer(function(req, res) {
    // We have to respond with something, otherwise the connections hang :(
    res.writeHead(404);
    res.close();
});
server.listen(port);

this._io    = io.listen(server, { "resource": "brokaw" });
this._trie  = new GlobTrie();

this._io.on("connection", function(conn) {
    new Brokaw.Server.Client(conn, self);
});
};

    new Brokaw.Server(8080);

我为index.html提供服务的代码如下:

// Hardcode *all* HTTP requests to this server to serve up index.html
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);
    }
);

有人可以建议如何整合两者,即修改顶级代码以提供我的index.html文件吗?

感谢任何评论,我一直在努力奋斗好几个小时!

问候,本。

1 个答案:

答案 0 :(得分:4)

有一个例子,取自官方Socket.IO homepage

服务器侧

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(80);

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);
  });
}

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

<强>客户端

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>