1

Can I convert a unique string into a slightly shorter one without running into collision risks? Or if not, can I somehow create a new unique code that's much shorter?

I'm working with socket.io, and I wanted to use the socket id of the client who sets up a session as a code to be shared in order for others to join that session, however a code such as Kf-uLxBxzB_8xwHgAAAC isn't exactly user friendly. I want people to be able to type the code if they choose to, so it needs to be as short as possible.

How is this kind of thing normally done? I'm using Node.js and client side JS.

  • Your title and first paragraph make no sense and have nothing to do with the rest of your (more sensible, though opinion based) question. – Amit Dec 14 '15 at 20:45
  • @Amit well, I was first thinking about somehow shortening the socket.io client id code. –  Dec 14 '15 at 20:47

2 Answers2

0

RISKY SOLUTION

You can change directly the id of the sockets when they connect:

socket  = io.connect('http://localhost');

socket.on('connect', function() {
    console.log(socket.io.engine.id);     // old ID
    socket.io.engine.id = 'new ID';
    console.log(socket.io.engine.id);     // new ID
});

SAFE SOLUTION

Or you can simply save sockets in an object in server side:

socket  = io.connect('http://localhost');
    var clients = {};

    socket.on('connect', function() {
        clients[customId] = socket.id;
    });


    var lookup = clients[customId];
Jairo
  • 350
  • 4
  • 12
  • In my opinion, the second suggestion here is probably the most robust since you're not modifying socket.io internals. The first approach could potentially break if socket.io releases an update in the future which operates on the assumption that internals such as the UIDs aren't modified. – Patrick Roberts Dec 14 '15 at 20:58
  • Well, usually socket.io breaks if you update 1.x anyway so... But i'm with you, the second approach is the right way. I always use the second one. – Jairo Dec 14 '15 at 20:59
0

Short answer: no, you can't shorten a UID without running into the risk of collision.

However, think about this from the user's perspective. What's so difficult about copying and pasting a code? It doesn't really matter how long it is, does it?

Another alternative would be to map the session UID to a semantic UID like heroku has, e.g. "blazing-mist-4652". See below for examples on how to generate names like that.

How can I programmatically generate Heroku-like subdomain names?

Community
  • 1
  • 1
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153