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

multiple unique clients using socket.io and express

multiple unique clients using socket.io and express

Problem

I am working with socket.io 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('socket.io').listen(app);
var clients = {};

app.listen(8080);

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

Solution

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 Socket.io.

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 socket.io would handle the talking:

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

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

Client:

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 Socket.io Readme for some better examples.

Solution courtesy of: Matt Molnar

Discussion

View additional discussion.



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

Share the post

multiple unique clients using socket.io and express

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×