Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

multiple unique clients using and express

multiple unique clients using and express


I am working with and Express, and I am struggling with having unique pages that all send and recieve messages from the server.

When I follow most tutorials, the server script starts out with something like this:

var app = require('express').createServer()
var io = require('').listen(app);
var clients = {};


// routing
app.get('/', function (req, res) {
    res.sendfile(__dirname + '/index.html');

and I can test my client app at localhost:8080. But what I want is to run a multiple client apps at something like http://localhost:8080/myApp/client1.html and http://localhost:8080/myApp/client2.html. When I try this, it returns something like:

Cannot GET /myApp/client1.html

My goal is to have two or more unique pages that can send messages to each other via sockets. Any help is greatly appreciated. I have been banging my head on this for way too long now.

Problem courtesy of: prototyper


I'm not very familiar with Express but instinct tells me get() would refer to a GET HTTP request and thus not a websocket. I think you're supposed to use Express to return HTML for page requests but real-time data transfer would be handled by

So, you would have Express return for the actual page requests:

app.get('/myApp/client1.html', function(blah){});
app.get('/myApp/client2.html', function(blah){});

Then would handle the talking:

var io = require('').listen(app);

io.sockets.on('connection', function (socket) {
  socket.on('msg', function (data) {
    io.sockets.emit('msg', {msg: data.msg});


var socket = io.connect('http://localhost:8080');
socket.on('msg', function (data) {
  //code to add data.msg somewhere on page
somebutton.on('click', function(e){
  socket.emit('msg', {msg:$(e.targetElement).value()});

Again, I don't know Express so I may have the syntax wrong but my gist is that you have two things going on that you need to handle separately. One is the returning of actual HTML pages, the other is the real-time data communication between the loaded pages. My examples are crude, check the Readme for some better examples.

Solution courtesy of: Matt Molnar


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

multiple unique clients using and express


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription