【问题标题】:Node.js - Serving an index.html file as well as serving web socketsNode.js - 提供 index.html 文件以及提供 Web 套接字
【发布时间】:2012-01-17 21:59:20
【问题描述】:

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

我的web socket代码如下:

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 文件吗?

感谢任何cmets,我已经挣扎了好几个小时!

问候,本。

【问题讨论】:

    标签: node.js static web socket.io


    【解决方案1】:

    有一个例子,摘自官方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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-20
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-08
      • 2020-08-08
      相关资源
      最近更新 更多