Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io with express

i have a project and I'm using socket.io with express ,

so what i need (i tried) is broadcasting a message but from an express action. is this possible i don't know how to get a reference to send or broadcast.

app.get('/', function(req, res) {
//i need to send messages from here 
});

Other things like using both express+socket.io is working with me :)

like image 236
ibmkhd Avatar asked Nov 04 '10 13:11

ibmkhd


People also ask

Can I use Socket.IO with Express?

Socket.IO can be used based on the Express server just as easily as it can run on a standard Node HTTP server.

What is Socket.IO VS Express?

Express http server gives request response model from client to server. Socket.io enables bidirectional communication channel between client and server.

How do I integrate Socket.IO in node?

In order to do it, you need to create an index. js file and install socket.io and express. You can use the following command: touch index. js && npm install express socket.io && npm install --save-dev nodemon .


1 Answers

As long as I understand,

Why not use the socket message type as an event instead of a http get or post? On the client side you would send a message via the websocket with let's say an event property.

So in your case:

<script>
  // Initialize socket.io ...

  // and then
  socket.send({event: 'homepage loaded', foo: 'bar'});
</script>

And on the server side:

var io = io.listen(server);

io.on('connection', function (client) {
  client.on('message', function (message) {
    if (message.event == 'homepage loaded') {
      client.broadcast(...);
    }
  });
});
like image 176
Philippe Rathé Avatar answered Oct 14 '22 14:10

Philippe Rathé