Ben
Ben

Reputation: 6086

Node.js - Serving an index.html file as well as serving web sockets

I am new to Node and Socket.io and attempting to get the below code running. It is designed to service WebSocket requests, however I would like to amend it to also serve static content such as index.html.

My web socket code is as follows:

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

And my code to serve the index.html is as follows:

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

Can anyone advise on how to integrate the two i.e. amend the top code to serve my index.html file also?

Appreciate any comments, and I have been struggling for many hours!

Regards, Ben.

Upvotes: 0

Views: 5461

Answers (1)

alessioalex
alessioalex

Reputation: 63683

There is an example, taken from the official Socket.IO homepage:

Server-side:

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

Client-side:

<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>

Upvotes: 3

Related Questions