Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

javascript - Creating Rooms in Socket.io

I would like to ask for your help. I'm having a hard time in my client side of socket.io, I would like to call this code in my client side to create a room in socket.io:

var rooms = [];
socket.on('create', function (roomname) {
    rooms[room] = room;
    socket.room = roomname;
            socket.join(roomname);
    subscribe.subscribe(socket.room);
});

I don't know if this is correct, if not please help me to correct this guys. I'm not that to pro in node js and sockets but i've already read their wikis. Is there any possible way to create room?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Rooms in Socket.IO don't need to be created, one is created when a socket joins it. They are joined on the server side, so you would have to instruct the server using the client.

socket.on('create', function (room) {
  socket.join(room);
});

In the example above, a room is created with a name specified in variable room. You don't need to store this room object anywhere, because it's already part of the io object. You can then treat the room like its own socket instance.

io.sockets.in(room).emit('event', data);

So to create a room from the client, this is what it might look like:

// client side code
var socket = io.connect();
socket.emit('create', 'room1');

// server side code
io.sockets.on('connection', function(socket) {
  socket.on('create', function(room) {
    socket.join(room);
  });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...