SlideShare una empresa de Scribd logo
1 de 8
PubNub
Messenger:
A Simple Chat
Room
by Dan Ristic
This is the first of a three-part series explaining how to build a multi-user messaging application using
jQuery Mobile and PubNub. You can read the series overview here.
Trying to plan out and begin building a multi user application can be a pretty tall order but in this part
we are going to throw caution to the wind and jump right in. In this post, we‟re going to cover:
1. Setting up jQuery Mobile and PubNub with a web page
2. Creating a basic chat room layout
3. Getting communication to and from a single chat room
This post will assume that you have a basic knowledge of JavaScript and HTML.
Installing the Libraries
The first thing you have to do is set up a single HTML page with jQuery Mobile and PubNub installed. I highly
recommend using the CDN versions for both libraries. This will make download times faster and also scale to millions of
users without having to deal with any servers (no need to use any back-end). I also created two files, screen.css and
messenger.js, and included them in my page. You can see the <head> section here:
<head>
<title>PubNub Messenger</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="apple-touch-icon href=icon.png">
<link rel="apple-touch-startup-image href=startup.png">
<link rel="icon" type="image/png" href="favicon.png">
<link href="https://fonts.googleapis.com/css?family=Ubuntu:300,400,700,400italic" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<link rel="stylesheet" href="css/screen.css" type="text/stylesheet" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script src="http://cdn.pubnub.com/pubnub-3.4.4.js"></script>
<script src="js/messenger.js"></script>
</head>
Creating the Page
Now we just need something pretty for the user to look at. Luckily with jQuery Mobile, this is fairly easy to do. The
package already comes with several themes built in and allows you to create a page using basic components which is
great for building a mobile user interface quickly. Our chat room page will have a list of messages, a send button, and a
text box to type in. The code to set this up looks like this:
<!-- Chat Page -->
<div data-role="page" id="chatPage" data-theme="c" class="type-interior">
<div data-role="content">
<div data-role="header" data-position="fixed" data-tap-toggle="false">
<h1>Pub Messenger</h1>
</div><!-- /header -->
<div data-role="content">
<ul data-role="listview" id="messageList">
<!-- <li><span class="username">User123:</span>This is my message.</li> -->
</ul>
</div>
<div data-role="footer" data-theme="c">
<textarea id="messageContent"></textarea>
<div class="ui-grid-a">
<div class="ui-block-a"><a href="#" id="sendMessageButton" data-role="button">Send Message</a></div>
<div class="ui-block-b"><a href="#" id="backButton" data-rel="back" data-role="button">Chat Rooms</a></div>
</div>
</div>
</div><!-- /content -->
</div><!-- /page -->
This page, although with some small styling issues, should suffice for the purposes of this part of the
tutorial. In another part of this series, I will talk more about how to get the layout to play nicely and be a
little more responsive. Also ignored in this part is a “chat rooms” button that will take the user back to
the list of saved chat rooms.
One of the best parts of this user interface is that it is completely cross platform. It works on major
desktop browsers and most mobile phones. At PubNub, we look for this kind of out-of-the-box cross
platform functionality not only in our personal framework, but also the third party ones we utilize.
Making Magic Happen
Time for the final step: Making the magic happen. This is done by hooking up our PubNub API to our
chat interface using JavaScript. Our users will then be able to send messages to a channel and listen
for messages from other users.
See the next slide for the code to set this up:
$(document).ready(function () {
// Initialize the PubNub API connection.
var pubnub = PUBNUB.init({
publish_key: 'demo',
subscribe_key: 'demo'
});
// Grab references for all of our elements.
var messageContent = $('#messageContent'),
sendMessageButton = $('#sendMessageButton'),
messageList = $('#messageList');
// Handles all the messages coming in from pubnub.subscribe.
function handleMessage(message) {
var messageEl = $("<li class='message'>"
+ "<span class='username'>" + message.username + ": </span>"
+ message.text
+ "</li>");
messageList.append(messageEl);
messageList.listview('refresh');
// Scroll to bottom of page
$("html, body").animate({ scrollTop: $(document).height() - $(window).height() },
'slow');
};
// Compose and send a message when the user clicks our send message button.
sendMessageButton.click(function (event) {
var message = messageContent.val();
if (message != '') {
pubnub.publish({
channel: 'chat',
message: {
username: 'test',
text: message
}
});
messageContent.val("");
}
});
// Also send a message when the user hits the enter button in the text area.
messageContent.bind('keydown', function (event) {
if((event.keyCode || event.charCode) !== 13) return true;
sendMessageButton.click();
return false;
});
// Subscribe to messages coming in from the channel.
pubnub.subscribe({
channel: 'chat',
message: handleMessage
});
});
If you have used the PubNub API before, some of this should look pretty familiar. If this is your first
PubNub project you can do a quick review of our JavaScript Beginners Tutorial. To communicate with
PubNub servers, you need to give the user access using a publish and/or a subscribe key. Be sure to
replace the `demo` keys with your own when testing this out so you can track the data back in our
PubNub administration panel.
After that, we use jQuery to grab references to some of our interface elements on the screen.
Personally I don‟t believe this is a scalable approach to JavaScript development, but for pedagogical
reasons this was easier.
The handle message function is what gets called when PubNub gets a real-time message from
another user in the channel. It creates a list item element, inserts the message and username, and
refreshes the list view which adds all of jQuery Mobile‟s fancy list interface and touch capabilities. We
can even throw in a scrolling animation for flavor.
Now we get to the message sending. All we do here is read the
message the user wrote and make sure they actually typed
something, then call publish with PubNub. This is all you have to do
and our message is shooting across the internet at light speed
(depending your ISP).
Finally we wrap it up by telling PubNub to call handleMessage when
we get a message from the chat channel . I also threw in a handler so
the user can hit enter instead of clicking on send message. As an
application developer, I cannot stress how important it is to throw in
shortcuts for your users. Every user has their own way of working
(think „terminal guru‟ vs. „grandma‟) and it is important to be usable for
your entire audience.
That is pretty much it for part one. We setup a simple chat program
using PubNub and jQuery Mobile which allows all our users to chat
together in one room. If you believe that one room isn‟t enough, then
be sure to check out the upcoming Part 2 of this series where we will
expand on the messenger for multiple chat rooms and more.

Más contenido relacionado

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 

Destacado

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Destacado (20)

Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 

PubNub Messenger: A Simple Chat Room (Part 1 of 3)

  • 2. This is the first of a three-part series explaining how to build a multi-user messaging application using jQuery Mobile and PubNub. You can read the series overview here. Trying to plan out and begin building a multi user application can be a pretty tall order but in this part we are going to throw caution to the wind and jump right in. In this post, we‟re going to cover: 1. Setting up jQuery Mobile and PubNub with a web page 2. Creating a basic chat room layout 3. Getting communication to and from a single chat room This post will assume that you have a basic knowledge of JavaScript and HTML.
  • 3. Installing the Libraries The first thing you have to do is set up a single HTML page with jQuery Mobile and PubNub installed. I highly recommend using the CDN versions for both libraries. This will make download times faster and also scale to millions of users without having to deal with any servers (no need to use any back-end). I also created two files, screen.css and messenger.js, and included them in my page. You can see the <head> section here: <head> <title>PubNub Messenger</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <link rel="apple-touch-icon href=icon.png"> <link rel="apple-touch-startup-image href=startup.png"> <link rel="icon" type="image/png" href="favicon.png"> <link href="https://fonts.googleapis.com/css?family=Ubuntu:300,400,700,400italic" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" /> <link rel="stylesheet" href="css/screen.css" type="text/stylesheet" /> <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script> <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script> <script src="http://cdn.pubnub.com/pubnub-3.4.4.js"></script> <script src="js/messenger.js"></script> </head>
  • 4. Creating the Page Now we just need something pretty for the user to look at. Luckily with jQuery Mobile, this is fairly easy to do. The package already comes with several themes built in and allows you to create a page using basic components which is great for building a mobile user interface quickly. Our chat room page will have a list of messages, a send button, and a text box to type in. The code to set this up looks like this: <!-- Chat Page --> <div data-role="page" id="chatPage" data-theme="c" class="type-interior"> <div data-role="content"> <div data-role="header" data-position="fixed" data-tap-toggle="false"> <h1>Pub Messenger</h1> </div><!-- /header --> <div data-role="content"> <ul data-role="listview" id="messageList"> <!-- <li><span class="username">User123:</span>This is my message.</li> --> </ul> </div> <div data-role="footer" data-theme="c"> <textarea id="messageContent"></textarea> <div class="ui-grid-a"> <div class="ui-block-a"><a href="#" id="sendMessageButton" data-role="button">Send Message</a></div> <div class="ui-block-b"><a href="#" id="backButton" data-rel="back" data-role="button">Chat Rooms</a></div> </div> </div> </div><!-- /content --> </div><!-- /page -->
  • 5. This page, although with some small styling issues, should suffice for the purposes of this part of the tutorial. In another part of this series, I will talk more about how to get the layout to play nicely and be a little more responsive. Also ignored in this part is a “chat rooms” button that will take the user back to the list of saved chat rooms. One of the best parts of this user interface is that it is completely cross platform. It works on major desktop browsers and most mobile phones. At PubNub, we look for this kind of out-of-the-box cross platform functionality not only in our personal framework, but also the third party ones we utilize. Making Magic Happen Time for the final step: Making the magic happen. This is done by hooking up our PubNub API to our chat interface using JavaScript. Our users will then be able to send messages to a channel and listen for messages from other users. See the next slide for the code to set this up:
  • 6. $(document).ready(function () { // Initialize the PubNub API connection. var pubnub = PUBNUB.init({ publish_key: 'demo', subscribe_key: 'demo' }); // Grab references for all of our elements. var messageContent = $('#messageContent'), sendMessageButton = $('#sendMessageButton'), messageList = $('#messageList'); // Handles all the messages coming in from pubnub.subscribe. function handleMessage(message) { var messageEl = $("<li class='message'>" + "<span class='username'>" + message.username + ": </span>" + message.text + "</li>"); messageList.append(messageEl); messageList.listview('refresh'); // Scroll to bottom of page $("html, body").animate({ scrollTop: $(document).height() - $(window).height() }, 'slow'); }; // Compose and send a message when the user clicks our send message button. sendMessageButton.click(function (event) { var message = messageContent.val(); if (message != '') { pubnub.publish({ channel: 'chat', message: { username: 'test', text: message } }); messageContent.val(""); } }); // Also send a message when the user hits the enter button in the text area. messageContent.bind('keydown', function (event) { if((event.keyCode || event.charCode) !== 13) return true; sendMessageButton.click(); return false; }); // Subscribe to messages coming in from the channel. pubnub.subscribe({ channel: 'chat', message: handleMessage }); });
  • 7. If you have used the PubNub API before, some of this should look pretty familiar. If this is your first PubNub project you can do a quick review of our JavaScript Beginners Tutorial. To communicate with PubNub servers, you need to give the user access using a publish and/or a subscribe key. Be sure to replace the `demo` keys with your own when testing this out so you can track the data back in our PubNub administration panel. After that, we use jQuery to grab references to some of our interface elements on the screen. Personally I don‟t believe this is a scalable approach to JavaScript development, but for pedagogical reasons this was easier. The handle message function is what gets called when PubNub gets a real-time message from another user in the channel. It creates a list item element, inserts the message and username, and refreshes the list view which adds all of jQuery Mobile‟s fancy list interface and touch capabilities. We can even throw in a scrolling animation for flavor.
  • 8. Now we get to the message sending. All we do here is read the message the user wrote and make sure they actually typed something, then call publish with PubNub. This is all you have to do and our message is shooting across the internet at light speed (depending your ISP). Finally we wrap it up by telling PubNub to call handleMessage when we get a message from the chat channel . I also threw in a handler so the user can hit enter instead of clicking on send message. As an application developer, I cannot stress how important it is to throw in shortcuts for your users. Every user has their own way of working (think „terminal guru‟ vs. „grandma‟) and it is important to be usable for your entire audience. That is pretty much it for part one. We setup a simple chat program using PubNub and jQuery Mobile which allows all our users to chat together in one room. If you believe that one room isn‟t enough, then be sure to check out the upcoming Part 2 of this series where we will expand on the messenger for multiple chat rooms and more.