1

Here's what I tried to do:

server.js

app = require('express.io')();
app.http().io();

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

app.put('/create', function(req, res) {
    req.io.route('articles');
});

app.io.route('join', function(req) {
    req.io.join(req.data);
    req.io.room(req.data).broadcast('newUser', {});
});

app.io.route('articles', function(req) {
    var message = {
        message: 'Article created'
    };
    req.io.room(req.data).broadcast('created', message);
    req.io.respond(message);
});

app.listen(3000);

client.html

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
    io = io.connect();

    io.emit('join','articles');

    io.on('created', function(data) {
        alert(data.message);
    });

    io.on('newUser', function(data) {
        alert('New user');
    });

    $.ajax({
        url: 'http://localhost:3000/create',
        data: 'articles',
        type: 'PUT'
    }).done(function(res) {
        alert('AJAX succeded');
    }).fail(function(res) {
        alert('AJAX failed');
    });
</script>

Problem was this line of code on the server:

req.io.room(req.data).broadcast('created', message);

gives the following error:

Object #<Object> has no method 'room' at Object.articles

The objective was to broadcast a message to a room after a request to '/created' was made, but not to the client that made the request. I've used app.io.room to broadcast but that sends to all clients, including the client that made the request, and I don't want that.

So my question is if it can be done and so what am I doing wrong, but if It can't, well a little bit of info about why not would be nice :)

tdlopes
  • 11
  • 2

0 Answers0