How do I serve the initial page in websockets


Ok so my question is concerning the websockets api...NOT npm install websocket

Here's my problem.

I have written a little websockets server that can receive a message, interpret the textual message and send it back with a little extra text. Simple enough.

The message comes from an index.html file with a javascript...script written in it. Everything works as expected. The node server runs locally on my machine and when I want to test it out I just start the server then double click the index.html file which runs the script, which starts a new connection with node and done.

What I want is to be able to navigate my browser to "localhost" and the server start by giving the client the index.html file, which in turn will establish a connection with the server.

How can the user get the index.html file by simply navigating to a url (localhost in my case), if a connection is required to get the index.html file. In it looks like this:

app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {});

If my question is still unclear here is a rewording: A user needs to be able to go to my url (localhost since node is running locally) and receive index.html. Like, all requests to the root receive an index.html file within a public directory.

Problem courtesy of: Captainlonate


The module you are using includes a complete example of how to use it with Express. It looks like it's written for the Express 2 API, so you have to tweak it if you're using Express 3:

var app = require('express')()
  , http = require('http')
  , server = http.createServer(app)
  , WebSocketServer = require('websocket').server;

var wsServer = new WebSocketServer({
    httpServer: server

Solution courtesy of: josh3736


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.