0

what I want to do is be able to create a room from the client but as if it was an object. For example: I have a class called "room", this class has let's say 3 events implemented so when you create a new room you can trigger those events in each. Is this possible? Here's my server code:

var express= require('express');
var app= express();
var server=require('http').createServer(app);
var io=require('socket.io')(server);
var channel= io.of('/arduino');
var bodyParser= require('body-parser');

server.listen(80, function(){
  console.log("Server corriendo en puerto 80");
});

io.on('connection', function(socket){
  console.log("Se conecto alguien por Socket");

  socket.on('new-message', function(data) {
    console.log(data);
    console.log("Nuevo mensaje");
    socket.emit('messages', data);
  });

  socket.on('JSON', function (data) {
    var jsonStr = JSON.stringify(data);
    var parsed = ParseJson(jsonStr);
    console.log(parsed);
  });
});


channel.on('connection', function(socket){
  console.log("Se conectaron al canal 'arduino' ");
    socket.on('new-message', function(data){
              console.log("Sensor:");
              console.log(data);
              channel.emit("messages", data);
      });
});


app.use(bodyParser.json());


app.get('/',function(req,res){
  console.log('555555555');
    res.status(200).send('GET TEST');
  });

app.post('/',function(req,res){
  console.log("post TEST");
  datos=req.body;
  console.log(datos);
  res.end("fin");
  });
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140

1 Answers1

0

Knowing the difference between rooms and namespaces is important for deciding what to go with :

namespaces are connected to by the client using io.connect(urlAndNsp) (the client will be added to that namespace only if it already exists on the server)

rooms can be joined only on the server side (although creating an API on the server side to enable clients to join is straightforward)

You can define socket events specific for a namespace, but the client wont be able to connect if that namespace hasn't been defined previously in the server-side.

Read More : Rooms vs Namespaces


I think that the easiest solution for handling different channels, including dynamic channel names (created from the client) is to use rooms

Room Join/Leave from Client :

A socket.io-client can be subscribed to multiple rooms, I gave an answer with a method for :

Making server.side room subscribe/unsubscribe events that can be triggered from the client

It also explains how to get correctly the list of rooms a disconnecting client was subscribed to so a message to those rooms may be delivered to notify the client left.

Community
  • 1
  • 1
EMX
  • 6,066
  • 1
  • 25
  • 32
  • Thank you! I honestly thought rooms and namespaces were the same thing, I'm only a beginner as you can see. This solves it. – user3474792 Aug 24 '17 at 18:36