S
S
Sarclin2016-09-10 00:47:07
Node.js
Sarclin, 2016-09-10 00:47:07

How to connect a user to sockets using an invite link?

I'm trying to do the following:
The first user visits the site (localhost in the example), copies a pre-generated link like " http://localhost:8080/room_id " and sends it to another user.
The second user follows the link and they both need to connect to the same socket in the room.
What's the catch:
1) It must be done without (!) using Express. Only node.js and socket.io.
2) I don't know how to process such url in handler.

var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs').
url = require('url');
var counter;
var rooms = []; //кол-во комнат
var urlRoom;
app.listen(8080);

function handler(req, res) {
  var path = url.parse(req.url).pathname;
  switch(path) {
    case '/':
      fs.readFile(__dirname + '/index.html',
      function(err, data) {
        if (err){
          res.writeHead(404);
          return res.end('Page doesn\'t exist - 404');
        } else {
          counter = 1;
          res.writeHead(200, {'Content-Type': 'text/html'});
          res.write(data,'utf8');
          res.end();
        }
      });
      break;

    default:
      res.writeHead(404);
      res.write('Page doesn\'t exist - 404');
      res.end();
      break;
  }
};

io.sockets.on('connection', function(socket) {
  var roomId = Math.round((Math.random()*1000000));
  addRoom(roomId);
  var room = getRoomById(roomId);

  socket.on('addNew', function(data) {
    urlRoom = data.url+''+roomId;
    console.log(urlRoom);
    var admin = false;
    if (isEmptyRoom(roomId)) {
      admin = true;
      socket.emit('inviteLink', {'inviteLink': urlRoom});
    } else {
      socket.broadcast.to(roomId).emit("join", {"start": "start"});
    }
    socket.join(roomId);
    socket.emit('start');
                room.user++;
  });
});

function addRoom(roomId) {
  var room = new Object();
  room.id = roomId;
  room.max = 2;
  room.user = 0;
  room.title = "";
  rooms.push(room);
}
function getRoomById(roomId) {
  for (i = 0; i<rooms.length; i++) {
    room = rooms[i];
    if (room.id == roomId) {
      return room;
    }
  }
  return null;
}
function isFullRoom(roomId) {
  var room = getRoomById(roomId);
  if (room.user == 2) {
    return true;
  } else {
    return false;
  }
}
function isEmptyRoom(roomId) {
  var room = getRoomById(roomId);
  if (room.user == 0) {
    return true;
  } else {
    return false;
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sarclin, 2016-09-13
@Sarclin

I decided. If suddenly someone needs it - an example of how to solve it. There is a limit of 2 users in one room and some "protection" from connecting to an uncreated room. Did not finish deleting the room after the user disconnected.

var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
url = require('url');

app.listen(8080);

function handler(req, res) {
  var urlParse = url.parse(req.url);
  if (urlParse.path == '/') {
    //если пользователь зашел на главную
    fs.readFile(__dirname + '/index.html',
    function(err, data) {
      if (err){
        res.writeHead(404);
        return res.end('Page doesn\'t exist - 404');
      } else {
      res.writeHead(200, {'Content-Type': 'text/html'});
        //отдаем страницу клиенту
        res.write(data,'utf8');
        res.end();
      }
    });
  } else if (urlParse.search) {
    fs.readFile(__dirname + '/index.html',
    function(err, data) {
      if (err){
        res.writeHead(404);
        return res.end('Page doesn\'t exist - 404');
      } else {
      res.writeHead(200, {'Content-Type': 'text/html'});
        //отдаем страницу клиенту
        res.write(data,'utf8');
        res.end();
      }
    });
  } else {
    res.writeHead(404);
    res.write('Page doesn\'t exist - 404');
    res.end();
  }
};
var rooms = [];
io.sockets.on('connection', function(socket) {
  //событие подключение нового пользователя
  socket.on('connect_new_user', function() {
    //генерируем id комнаты
    var room = Math.round(Math.random() * 1000000);
    //подключаем сокет к комнате
    socket.join(room);
    //отправляем клиенту id комнаты
    socket.emit('addRoom', {'room': room});
    addRoom(room);
  });
  //событие подключение второго пользователя
  socket.on('connect_second_user', function(data) {
    //получаем к-во пользователей в комнате
    var playersCount =  io.clients(function(err, clients) {
      if(err) throw error;
    });
    //если кол-во пользователей в комнате 2 или более - комната полна
    if (playersCount.server.eio.clientsCount-1 >= 2) {
      console.log('Room is full');
      return;
    } 
    if (!containsTheRoom(data.roomId)) {
      socket.emit('message', {message: 'Room not found'});
    } else {
    //если нет - подключаем пользователя к комнате с переданным id
      socket.join(data.roomId);
    //отправляем сообщение всем
      io.sockets.to(data.roomId).emit('message', {message: 'message for all'});
    //и себе
      socket.to(data.roomId).emit('message', {message: 'message for you'});
      console.log('connect in room');
    }
    console.log(rooms);
  });
});

function addRoom(roomId) {
  rooms.push(roomId);
}
function containsTheRoom(roomId) {
  for (var i=0; i < rooms.length; i++) {
    if (rooms[i] == roomId) {
      return true;
    } else {
      return false;
    }
  }
}

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="/socket.io/socket.io.js"></script>
  </head>
  <body>
    <script>
      var socket = io.connect('http://localhost:8080');

      socket.on('connect', function() {
        var path = window.location.search;
        if (path == '') {
          socket.emit('connect_new_user');
        } else {
          socket.emit('connect_second_user', {'roomId': path.substr(1)});
        }
      });
      socket.on('addRoom', function(data) {
        document.querySelector('#output').innerHTML=
        window.location.href+'?'+data.room;
      });
      socket.on('message', function(data) {
        document.write(data.message);
      });
    </script>
    <div id="output"></div>
  </body>
</html>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question