Real-Time Gaming Blog

Create Chatrooms and Multiple Channels On Demand Tutorial

4 min read Michael Carroll on Aug 13, 2014
Try PubNub Today

Free up to 1MM monthly messages. No credit card required.

Subscribe to our newsletter

By submitting this form, you are agreeing to our Terms and Conditions and Privacy Policy.

In this tutorial, we'll talk about how to create new channels to spawn chatrooms on demand for user-to-user private chat and spawning new game servers.

Waving Hand

Good News! We’ve launched an all new Chat Resource Center.

We recommend checking out our new Chat Resource Center, which includes overviews, tutorials, and design patterns for building and deploying mobile and web chat.

Take me to the Chat Resource Center →

create chatroomIn this tutorial, we’ll move on to talking about how to spawn an infinite amount of new channels to create chatroom(s) on demand. So far, all of our communication has happened over a couple static channels, so now we’re going to take that a step further with how to create chatroom(s) on demand.

Create Chatroom(s) and Spawning Infinite Channels on Demand

The ability to create new channels on demand is important for things like user-to-user private chat or spawning new multiplayer game servers. More broadly speaking, this tutorial applies to any situation where you need to create any number of channels.


We’ve now covered both building a multiplayer game lobby with a chatroom and the different ways we can use matchmaking to connect two different users. Here’s what we’ve covered so far:

This blog post is Part Seven of PubNub Developer Evangelist Ian Jennings‘s series on creating a multiplayer game with JavaScript.


Closures

Infinite is a big number, so we’ll need to employ some advanced Javascript concepts to keep our code in order. In this demo we’re going to harness the power of Javascript closures and object oriented programming to create an infinite number of chatrooms.

Closures

You’ll first need to sign up for a PubNub account. Once you sign up, you can get your unique PubNub keys in the PubNub Developer Portal. Once you have, clone the GitHub repository, and enter your unique PubNub keys on the PubNub initialization, for example:

Now, let’s take a look at an example of a Javascript closure.

The setTimeout(x, y) function waits y milliseconds to fire function x.

The output would look like:

The function setTimeout() waits an entire second before calling handle()handle() is still able to access the values of name and timeout even after the function has returned because it is in a closure.

An inner function always has access to the vars and parameters of its outer function, even after the outer function has returned. Read more: http://crockford.com/javascript/

Closures preserve the environment so that even a full second later, setTimeout() still has access to the variables defined within the scope of the parent function.

The function defined in the closure ‘remembers’ the environment in which it was created. Read more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

Closures are notoriously a difficult concept to grasp. I highly recommend reading the detailed explanation of closures provided by Mozilla. There are also some helpful explanations on Stack Overflow.

Chatroom Refactor

Let’s take a look at how we can use closures to dynamically create chatroom(s) on demand. Unlike previous chapters, we won’t be building off our previous code examples. Instead, we’re going to refactor the “Chatroom” example from the first chapter. Instead of defining everything globally, we store all of our variables within the Chatroom() object and make sure all variables are relative to that object rather than the global scope. Notice the similarities between Chatroom() and Alarm() from earlier.

We’ve covered most of this code before. The largest change is that it is now encapsulated within the Chatroom() function.

Infinite Chatrooms

Now, we’ll add an event the #spawn-chatroom click handler. When the button is clicked, we’ll call Chatroom(); to create chatrooms on demand with a new id and template.

Keeping Things Relative

Like the setTimeout() in our Alarm() example, even though the Chatroom() function returns immediately pubnub.subscribe() appends the message to the correct chatroom.

The message can come minutes or hours later. PubNub can even disconnect and reconnect. The environment will always know what specific .chat-output to append PubNub messages to because the closure has preserved the relationship between the subscribe call and the object that initiated it.

Create Chatrooms and Spawn Multiple Channels Demo

Check out the full demo embedded below, or check out the create chatroom demo on CodePen.

See the Pen Memewarz – Chatroom Spawn #2 by Ian Jennings (@ianjennings) on CodePen.0

Overload

But what about all the subscription calls? Won’t PubNub get overloaded? Is there a limit to the number of channels I can subscribe to? Will this clog the tubes?

Thanks to PubNub multiplexing, you can subscribe to as many channels as you want without worrying about latency. Channels are an abstract concept and don’t create any additional connections.

Instead, the messages are bundled together and distributed accordingly. If you look at the actual subscribe network headers, you can see every channel represented in the same single request.

fWSRyRZ

 

Networking in an object oriented way is exciting. This pattern is extremely empowering and you can use it to build almost anything in a organized and scalable fashion.

We’ll be using it in the future to create private chat from user to user and spawn game servers on demand.

More from PubNub

NPP and HIPAA: Notice of Privacy Practices Definition
Healthcare CategoryJan 6, 20235 min read

NPP and HIPAA: Notice of Privacy Practices Definition

A Notice of Privacy Practices (NPP) is one of the requirements of HIPAA and helps patients understand their personal data rights.

Michael Carroll

Michael Carroll

HIPAA Violation Examples
Healthcare CategoryJan 5, 20236 min read

HIPAA Violation Examples

HIPAA violations can be financially expensive and devastating to a brand. Examine some examples of HIPAA violations, and learn...

Michael Carroll

Michael Carroll

HIPAA Technical Safeguards: How To Protect Sensitive Data
Healthcare CategoryJan 5, 20236 min read

HIPAA Technical Safeguards: How To Protect Sensitive Data

HIPAA covered entities must follow the five technical safeguards to achieve HIPAA compliance and prevent data corruption.

Michael Carroll

Michael Carroll