Reputation: 23
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.
Upvotes: 0
Views: 1909
Reputation: 1520
or add a dynamic handler for your files:
app.get('/myApp/:file', function(req, res) {
res.sendfile(__dirname+'/'+req.param('file'));
});
or beef it up a little with a regex:
app.get(/^\/myApp\/(.+)\.html$/, function(req, res) {
res.sendfile(__dirname+'/'+req.params[0]);
});
Upvotes: 1
Reputation: 2542
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.
Upvotes: 1