PubNub RSS - Cloud-Hosted Broadcasting Service for Real-Time Messaging http://www.pubnub.com/ Mass Broadcast. Stream data to millions of users. Engage a live audience with real-time updates. Launch Sports Tickers, Push Finance and News. Many-to-Many Messaging. Community publish/subscribe. All clients transmit and receive. MMO Games, Chatrooms, Geolocation Sharing. <![CDATA[TechCrunch: Real-Time Messaging Startup PubNub Introduces Pulse To Facilitate One-To-One Communications]]> http://techcrunch.com/2012/06/13/pubnub-pulse/ TechCrunch: Real-Time Messaging Startup PubNub Introduces Pulse To Facilitate One-To-One Communications]]> <![CDATA[PubNub Launches New Cloud Service: PubNub Pulse]]> https://s3.amazonaws.com/pubnub/assets/press/PubNub_Pulse_Launch.pdf PubNub Launches New Cloud Service: PubNub Pulse]]> <![CDATA[PubNub Cloud Exceeds 1 Million Messages per Second]]> https://s3.amazonaws.com/pubnub/assets/press/PubNub_1M_Messages_per_Second.pdf PubNub Cloud Exceeds 1 Million Messages per Second]]> <![CDATA[PubNub A Cloud Service pairing Node.js]]> http://servicesangle.com/blog/2012/01/24/pubnub-a-cloud-service-for-node-js/ PubNub A Cloud Service pairing Node.js]]> <![CDATA[A PubNub-Powered Game for ImpactJS]]> http://www.pubnub.com/blog/impact-js

A PubNub-Powered Game for ImpactJS

ImpactJS is an HTML5 mobile and web games framework for building games quickly. PubNub has the ability to add Multiplayer Connectivity for your ImapctJS games. We want to make it super easy to provide and power your multiplayer games with PubNub. That's why today we're helping you get off the ground with a tutorial and basic plugin.

Watch on YouTube: http://youtu.be/mTQqSIaH7Lg

Multiplayer Game State

First, a note on the concept of state. State provides a difficult problem when it comes to making multiplayer games. The problem at hand is keeping track of where each on-screen entity is, including the values for the entity's attributes. In some situations, it may be ok to have each client blast out information and have the other clients update accordingly. But what if two clients disagree? Who's right?

To get around this, we need a authoritative middle-man. A server. In the context of PubNub, that's really a 'super client'. Nonetheless, we provide you a basic Node.js based server to accompany our plugin. In our case, we use the same Node.js instance that hosts the http server for ImpactJS to also be this server.

Multiplayer Collision Detection

But what about collision detection? This provides another challenge, because the server is not able to run the same canvas-based game code that the clients can in a browser. Despite Node.js being javascript-based, it requires a window object not present on the server. Our solution for the time being is the notion of player "ownership" of certain entities. When you define a entity in PubNub, you indicate whether an item always is controlled by a certain player, or if it is variable.

Let's take the example of a pong game. Each player is responsible for one paddle and during the game that will not change. Player 1 will never be able to say where Player 2's paddle is located, and vise-versa. The puck, however, will be a variable entity. When ever the puck moves, the server calculates which non-variable entity is the closest. That entity's owner will be in charge of the puck. In the case of pong, that occurs when the puck crosses the screen half-way point. In this way, collisions between variable entities and non-variable entities will always occur locally to the relevant player. It's not a perfect solution, and certainly it's susceptible to cheating, but for this early stage it suffices.

Before you get started, we're assuming you have a license and a copy of the ImpactJS code. You can grab them from the ImpactJS website. Once you get that, you'll need our plugin, which is located here. Finally, you'll want our tutorial code, located here. Drop the ImpactJS code in as /lib/impact in the root example directory (we intentially omited it, you'll need a license!) and drop the plugin as /lib/plugins/pubnub .

Got everything in the right place? Great. Now you'll need node.js installed for the basic server components, and a few modules. But like any true open-source hacker, you can get those easily enough.

You'll write your game logic in /lib/game/main.js. Here, you'll make your game extend PubNubGame like so:

ig.module(
'game.main'
)
.requires(
'impact.game',
...
'plugins.pubnub.game'
)
.defines(function(){
MyGame = ig.PubNubGame.extend({ ...

Similarly, you'll extend your entities to be PubNubEntities like this:

EntityPuck = ig.PubNubEntity.extend({ ...

It's easy! When you do this, you get some PubNub stuff out of the box, for free:
  1. Presence. When a client connects to your game, you'll want to know whether or not he's still there or it has disconnected. Just call initPlayer(PLAYERID) on the server side.
  2. Entity Auto-Update. After you run startGame(ARRAY_OF_PLAYERS, INITIAL_POSITIONS) , all entities will automatically update other entities with their current location and velocity.
  3. Appropriate Collision Detection also from startGame(...), clients will handle collisions that are local to their controlled entities.

Just a Starting Point

What we're releasing today is intended to help you get off the ground making a multiplayer games. There are some significant challenges when it comes to games. All canvas-based game frameworks render things using RequestAnimationFrame and not based on real time measurements. This means coordinating between two devises with different framerates is very challenging. We will continue to support our developer network in this area. We want PubNub to be the no-brainer choice when it comes to powering your next multiplayer game.

]]>
<![CDATA[Real-time meets Roar Engine's games mechanics API through our partnership with PubNub]]> http://blog.roarengine.com/2011/08/real-time-meets-roar-engines-games.html Real-time meets Roar Engine's games mechanics API through our partnership with PubNub]]> <![CDATA[Corona SDK Action-packed release!]]> http://blog.anscamobile.com/2011/08/action-packed-release/ Corona SDK Action-packed release!]]> <![CDATA[Will A Cooler Corona Make Tastier Mobile Apps?]]> http://www.informationweek.com/news/development/mobility/231003033 Will A Cooler Corona Make Tastier Mobile Apps?]]> <![CDATA[Ansca Mobile Partners with Mobile Monetization and Social Leaders to Add Powerful New Functionality to Corona SDK]]> http://www.benzinga.com/pressreleases/11/08/p1825638/ansca-mobile-partners-with-mobile-monetization-and-social-leaders-to-ad Ansca Mobile Partners with Mobile Monetization and Social Leaders to Add Powerful New Functionality to Corona SDK]]> <![CDATA[MuleSoft Announces Mule ESB Cloud Connector for EBay Company, Magento]]> http://www.marketwire.com/press-release/mulesoft-announces-mule-esb-cloud-connector-for-ebay-company-magento-1544781.htm MuleSoft Announces Mule ESB Cloud Connector for EBay Company, Magento]]> <![CDATA[What Is Pubnub? Asynchronous Imperative!]]> http://efgeeky.com/en/2011/07/27/what-is-pubnub-asynchronous-imperative/ What Is Pubnub? Asynchronous Imperative!]]> <![CDATA[Your Style Sheet in Realtime]]> http://www.pubnub.com/blog/update-your-style-sheet-in-real-time

Your Style Sheet in Realtime

First: sign-up for a PubNub account. You have always wanted to send CSS updates to your website or HTML5 mobile app in Realtime. How do you do this? It was hard before PubNub right? Change the value of the CSS in the text box below, then press "Broadcast CSS Changes" button. What will pressing that button do? This will broadcast the CSS in the text box below. The one called "Inline CSS". To EVERYONE, not just you. Seriously. Try it with a friend! You must both be on this page at the same time.

<!-- DIV to be Updated -->
<div id=update-this-with-css class=original-class>
    <p>This DIV will be updated via remote call.</p>
</div>

This DIV will be updated via remote call.

Element To Update
Inline CSS
- Everyone will see the change, INSTANTLY!

You can imagine pushing all sorts of changes on the fly using this method. Such as updating the entire look of an app or website. Also changing or adding new images in real-time. Even adding new content in real-time. Of course you will hide the Broadcast Button so only you can push changes on the fly. You must sign-up for a PubNub account.

<div id=pubnub></div>
<script src=http://cdn.pubnub.com/pubnub-3.1.min.js></script>
<script>(function(){
// -----------------------------------------------------------------------
// Define the channel to broadcast your updates on.
// In this case we are broadcasting updates to update a class-name
// -----------------------------------------------------------------------
var channel = 'update-your-styles-sheet-in-real-time';

// -----------------------------------------------------------------------
// On Click/Touch, "Broadcast CSS Update" to everyone.
// -----------------------------------------------------------------------
PUBNUB.bind( 'click', PUBNUB.$('send-css-update'), function() {
    PUBNUB.publish({
        channel : channel,
        message : {
            'element-id' : PUBNUB.$('element-id-to-update').value,
            'css'        : PUBNUB.$('inline-css').value
        }
    })
} );

// -----------------------------------------------------------------------
// On Receive Broadcast, Execute the CSS Updates.
// This happens for everyone who is on this page.
// -----------------------------------------------------------------------
PUBNUB.subscribe({
    channel  : channel,
    callback : function(message) {
        PUBNUB.attr(
            PUBNUB.$(message['element-id']),
            'style',
            message['css']
        );
    }
});
})();</script>

Have questions? Sign up and then contact us. Or Mention us @PubNub Twitter.

]]>
<![CDATA[PubNub Flash AS3]]> http://www.wikiflashed.com/wiki/PubNub PubNub Flash AS3]]> <![CDATA[Adding Secure Publishing To The PubNub Realtime Messaging Workflow]]> http://www.bennadel.com/blog/2217-Adding-Secure-Publishing-To-The-PubNub-Realtime-Messaging-Workflow.htm Adding Secure Publishing To The PubNub Realtime Messaging Workflow]]> <![CDATA[PubNub CFC A ColdFusion Wrapper]]> http://www.bennadel.com/blog/2214-PubNub-cfc-A-ColdFusion-Wrapper-For-The-PubNub-Realtime-Messaging-Platform.htm PubNub CFC A ColdFusion Wrapper]]> <![CDATA[Sending Client To Client]]> http://www.bennadel.com/blog/2213-Sending-Client-To-Client-Realtime-Messages-With-The-PubNub-JavaScript-Library.htm Sending Client To Client]]> <![CDATA[PubNub Streams Live Launch]]> http://www.pubnub.com/blog/streams

PubNub Streams Launch - Twitter Verified

What are Streams?

PubNub is the standard for real-time data push on mobile, tablet and web. And PubNub Streams are real-time live mobile and web widgets which you install on your website and mobile apps. As you can see in the sample image above, there is a chat stream and a Reddit Programming + Hacker News stream included in this product beta launch. PubNub Streams provide Live Real-time interactivity which allow people to communicate with each other. Additionally Streams can display all types of social data instantly in real-time. Look now and find just two Stream Apps listed today, however more are on the way!

PubNub Streams also provides a repository of free-to-install widgets. A place where you go to test and choose which widget to install. You may install rich chat programs, coupon streams, live rss readers, live stock tickers, live analytic tools and more. These widgets are built for mobile and web based clients and are no cost to you because it has the PubNub branded logo embedded.

There are more kinds of Streams in the build pipeline that will be interesting for markets in Social, Finance, E-Commerce, Gaming, etc.

@PubNub Exponential Growth on Twitter

PubNub Twitter Exponental Growth

Wohhh! See the sudden shift in the graph? This is our growth trend. Note that this growth change is pre-Streams launch. PubNub is growing at an amazing rate and we are excited to bring you products and services powering real-time data push for mobile and web.

PubNub is Twitter Verified

PubNub Twitter Verified

PubNub is Twitter verified. This is a milestone in our company's timeline and an opportunity to push our new Streams product. PubNub is the standard for real-time mobile and web data push. And Streams is the product which uses the Real-time Capabilities of the PubNub standard.

Streams Marketing Strategy

By providing rich live web and mobile widgets, we are promoting our brand. We do this by giving you ready-to-use live web and mobile widgets; capitalizing this opportunity to extend the PubNub brand. Our marketing strategy is successful and has led to PubNub being the standard for real-time data push on mobile, tablet and web.

Goals for Streams

You will see PubNub Streams installed on websites, mobile phones and tablets. There are more types of Streams on the way. Initially we launched this beta with a chat and news reader. Soon we will promote real-time live Ebay Plugins, Live GROUPON Widgets, coupon streams, Photo Stream Readers, E-commerce Customer Communication and flow monitoring, financial market data distribution (stock quotes, news), online betting and gaming, live bids for e-auctions, Web-based monitoring consoles, online communities with live user interaction (messaging, chat, presence) and more.

]]>
<![CDATA[Two Google Services to Monitor Your Brand's Web Presence]]> http://www.pubnub.com/blog/two-google-services-to-monitor-your-web-presence

Two Google Services to Monitor Your Brand's Web Presence

What are they saying about your Business and You? Approach a monitoring solution for your brand, business and person by running Google Alerts and Google Realtime. These services allow you to personally monitor your web presence. Not interested in a brand or business? Use Google Alerts and Realtime to watch trending topics like Obama.

Step 1: Go to Google Alerts

Step 2: Type Business Name

Now type the search term you are interested in. For example, type "pubnub", then click "Search".

Step 3: Notification Frequency

Select how often notifications should be delivered to your inbox.

Step 4: Volume of Results

Select the volume of results, This is the quality level of results.

Step 5: Pick your Email

Select the email address which will receive the notifications.

Step 6: Automatic Email Notifications

Your done! Automatically emails will be sent to you when your brand is mentioned somewhere on the web. Try the next tool for even faster results including Tweets.

Step 1: Go to Google Realtime

Step 2: Type your Search

What do you want to see results from? For example, type "pubnub", then click "Search".

Step 3: Sit and Watch

Your done! Note that this isn't a normal results page. New results will appear on the screen somewhat instantly as they are published on the web. You are armed with a full listing of Social and Web search results, updated and pushed to you as they happen.

]]>
<![CDATA[IM Chat Client with Voice Recognition in The Browser]]> http://www.pubnub.com/blog/im-chat-client-with-voice-recognition-in-the-browser

IM Chat Client with Voice Recognition in The Browser

The world's first IM Chat client with voice recognition in the browser. This chat requires Facebook for user verification and for your photo. Turn on your speakers, the text transmitted will be re-spoken by your computer's voice.

You must have Google Chrome 11+ to speak. However you may watch people who are speaking.

Loading...

Press Microphone and Speak
yes!
hey does this work

The First Browser Based Voice IM provided by PubNub

First, you need Google Chrome version 11 or greater to participate and transmit your voice via a web browser. Now click the microphone icon and speak into your computers mic. The voice processor will convert your speech into text sending Next your computer will send this meta speech to everyone who is on this website. Upon receiving this broadcast, each person's computer will prepare the message and re-speak it in both text and in a simulated voice. This technology has been around and is still pretty new. Today you are able to test this technology yourself in your web browser. This Chat IM App is written in JavaScript and HTML5. The source code is listed lower in this page. Continue reading to learn more about TTS Text To Speech and STT Speech To Text.

Text to Speech on CNET TV

CNET's Seth Rosenblatt is testing Google Chrome's Speech To Text using the Google Translate inteface provided by Google. Click here to watch the video explaining Google's New Chrome Speech to Text Tech.

iPhone Voice Control

Donald Bell talks about the voice control feature of the iPhone. This Speech To Text feature is old tech these days on mobile. However it is recent news for a web browser to support such technology.

Text-To-Speech and Speech-To-Text

There are several APIs available for TTS Text To Speech. These TTS APIs provide a way for your computer and GPS Navigator to speak aloud to you driving directions and word translations. Google's REST API is the most simple to use:

http://translate.google.com/translate_tts?tl=en&q=I+like+PubNub
A commercially available TTS API called iSpeech gives access to a rather complex yet powerful API providing flexible voice control including gender and accents. iSpeech has many SDKs and cover nearly every mobile device. TTS may be used to read a book allowed while driving or help children to read at an early age.

STT Speech To Text is the opposite. Record your voice and your computer will interpret the words you have spoken and translate them onto your computer screen as plain text. Voice Controlled Systems use this kind of tech. Both STT and TTS are demonstrated on this page, in a web browser.

Source Code

Here is the source code for this app. Note that a direct Copy and Paste will result in Facebook Errors. However it is a good start if you wish to peek under the hood.

]]>
<![CDATA[The Humble Frozenbyte Bundle]]> http://www.humblebundle.com/ The Humble Frozenbyte Bundle]]> <![CDATA[Erlang <pub>PubNub</pub> Client and Chat Tutorial]]> http://blog.erlware.org/2011/04/10/erlang-pubnub-client-and-chat/ Erlang PubNub Client and Chat Tutorial]]> <![CDATA[Erlang Chat for <pub>PubNub</pub> on Github]]> https://github.com/tsloughter/epubnub_chat Erlang Chat for PubNub on Github]]> <![CDATA[Silverlight API for <pub>PubNub</pub>]]> http://www.pubnub.com/tutorial/silverlight-realtime-graph-using-pubnub-api
WANRING: This content is OLD!

Silverlight Real-time Graph using PubNub

PubNub messaging capabilities can be used on browser plug-ins like Flash and Silverlight. In this tutorial, we will see how to use PubNub Silverlight API in Silverlight.

This experiment is very simple. We are going to develope a Graph in Silverlight that receives realtime updates from another application through PubNub APIs.

Graph in Silverlight

Silverlight is one of the finest tool that is used to develope rich internet applications. In this experiment Silverlight is used to build a Graph that depicts the Monthly budget. Data-source for this graph is from another Silverlight application.

The magic of PubNub Silverlight API is to constantly listen to a PubNub channel to look for new data and attach it to the graph. You can see the Graph in the image below.

 

PubNub is a messaging service on cloud. Messages can be published into a specific channel through a server and configure various clients listening to this channel.

In our case webpage that hosts the Flash chart is the client, listening to the stock updates flowing through a specific PubNub messaging channel using PubNub Silverlight API.

Include the PubNub Class to your Silverlight Chart application. Follow the following steps to start listen to the data for your chart

Step 1: Create a Pubnub Object

Following snippet will show you how instantiate a Pubnub class. You need to provide 4 parameters as follows

	//Instantiate PubNub Class
	PubnubClass pubnub = new PubnubClass(
	    "demo", // PUBLISH_KEY
	    "demo", // SUBSCRIBE_KEY
	    "",     // SECRET_KEY
	    false   // SSL_ON?
	);

You need to have 2 keys namely - PUBLISH_KEY, SUBSCRIBE_KEY Grab your API Keys here.

Step 2:

Tune on to a specific channel and start listening to messages. Make a call to the "Subscribe(<Channel>)" method on PubNub object created above. You need to pass the 'Channel Name' as a parameters to this method as shown in the below snippet. This method starts listening on the specified channel continously. More details on the implementation of Silverlight API can be found in PubNub Silverlight API.

	pubnub.subscribe("test-channel");
	

Step 3:

Now Need to check for the incoming messages on the PubNub object's "ReturnMessage" property. If you make the return message property bindable, then you dont have to do anything. But in our case we are not making it bindable. We constantly check of any change in the return message to re-bind the chart.

pubnub.ReturnMessage

	object[] objArray = pubnub.ReturnMessage as object[];

Now Lets implement a simple Server application. Server Application is going to be another silverlight application that will perform the Publish.

Publish Component

The role of the server here is very simple. It will publish messages into a specific channel. Lets call it a Messaging Server. You can see the Messaging Server in the image below.

There are two inputs, Channel Name & Content to broadcast. There is a button at the bottom, which will publish the message into the specified channel using a button at the bottom, which will publish the message into the specified channel using PubNub C# API.

Publishing the message using PubNub API is very simple. OnClick() of button is defined as in the code snippet below.

Publish()

	object obj = new List<double>() { {100}, {200}, {300} };
	pubnub.publish("test-channel", obj);

Publishing messages involves 2 steps:

Step 1. Instantiate the PubNub API. You need to have 3 keys namely - PUBLISH_KEY, SUBSCRIBE_KEY & SECRET_KEY to instantiate PubNub API as in the above code snippet.

Grab your API Keys here.

Step 2. Make a call to the "Publish(<Channel>, <Message>)" method on PubNub API. You need to pass the 'Channel Name' and the 'Message to publish' as parameters to this method as shown in the above snippet. Message can be any object. Your message is now published into the specified channel on Cloud. This method internally makes an HttpWebRequest to carryout the operation. More details on the implementation of Publish can be found in PubNub C# API.

In our case the amount spent on different category of expenses are published through the channel to update the graph.

Click here to download the source code for this solution.

Author:
Kris.Ram, Integration Specialist
Minnesota, USA

]]>
<![CDATA[Play Video ► Corona SDK <pub>PubNub</pub> Developers Kitchen]]> http://www.youtube.com/watch?v=f3Y2JAoSJfw&feature=youtu.be Play Video ► Corona SDK PubNub Developers Kitchen]]> <![CDATA[First Ever Corona SDK Developers Kitchen]]> http://blog.anscamobile.com/2011/03/recap-first-ever-corona-sdk-developers-kitchen/ First Ever Corona SDK Developers Kitchen]]> <![CDATA[Wots Is Name?]]> http://www.pubnub.com/blog/wots-is-name

Wots Is Name?

A new game created by Fixdit Ltd. offers advanced multiplayer capabilites with engadging social gameplay. 'Wots Is Name?' App puts your Facebook friends in the game.

Play: Wots Is Name? on Tuesday 22nd March 2011.

'Wots Is Name?' is a 'guess who' format game using your Facebook friends. By asking your opponent YES/NO answer questions your aim is to identify your mystery person. The questions you ask can be general like "Are they female?" or personal like "Are they one of my ex's?"

How to Play Video

How to Play Video 'Wots Is Name'

'Wots Is Name?' is the new, one of a kind, 2 player game available for iPhone, iPad and iPod touch. Coming soon to Android. Available in the App Store now!

Fixdit is an interactive web technology team building mobile apps with social media and social engadgement.

Play: Wots Is Name? the classic and much loved board game format meets your Facebook friends. 'Wots Is Name' is the new 2 player game of deduction. Played face-to-face, you identify your opponent's mystery person by asking them simple YES/NO questions and matching a face to a name.

You decide on the line of questioning, the possibilities are endless. While playing Wots Is Name for iPhone, iPad and iPod Touch, why not ask: "Are they obviously posing?"

Install App: Wots Is Name?

]]>
<![CDATA[Build Real-time Apps Easy]]> http://www.pubnub.com/blog/build-real-time-web-apps-easy

Easy Real-time Apps

Chat in 10 lines of JavaScript. Quickest way to write Real-time Apps on mobile and web.

10 lines:

Enter Chat and press enter
<div><input id=input placeholder=you-chat-here /></div>

Chat Output
<div id=box></div>

<div id=pubnub pub-key=demo sub-key=demo></div>
<script src=http://cdn.pubnub.com/pubnub-3.1.min.js></script>
<script>(function(){
var box = PUBNUB.$('box'), input = PUBNUB.$('input'), channel = 'chat';
PUBNUB.subscribe({
    channel  : channel,
    callback : function(text) { box.innerHTML = (''+text).replace( /[<>]/g, '' ) + '
' + box.innerHTML; } }); PUBNUB.bind( 'keyup', input, function(e) { (e.keyCode || e.charCode) === 13 && PUBNUB.publish({ channel : channel, message : input.value }); } ); })();</script>

Build Apps Fast

Quickest way to write Real-time Apps on mobile and web.

Cut Development Time

PubNub's framework dramatically reduces your coding. Tasks like sending and receiving data take only one function call. And your code instantly updates in web and mobiles apps, for rapid testing.

The network infrastructure and scaling is taken care of for you so you spend time building your app, not infrastructure.

Start using PubNub Today

Develop Across Platforms

PubNub has the only complete solution for developing across platforms and OS versions. You can write once and build Web, iOS and Android Apps. PubNub will automatically broker your connections from web to phones to tablets to everywhere.

Security

PubNub provides a default baseline level of security, with optional encryption and messaging signing support for high-security applications. Download Security Doc (page 2).

How it Works

PubNub is designed to make Real-time Mobile and Web Apps easier with two functions to pass data back and forth using JavaScript.

PubNub is an RPC Network which takes care of XHR, routing, serialization and parsing so that you don't have to deal with AJAX. It's built using JavaScript overblown with every optimization under the sun.

The example app is a real-time chat room written in 10 lines.

PubNub creates a namespace "PUBNUB", with publish (send) and subscribe (receive) functions. Messages published are automatically synced in real-time with clients subscribed.

PubNub offers an abstraction layer to make calling remote functions very simple without worrying about ports or sockets. It is a higher-level interface for making network programming easy.

Start using PubNub Today

iPhone, iPad, Android, Tablets. IE4+, Safari 1+, Opera, Chrome 1+, FireFox 1+, everything.

Next we are...

Building a  DARKNET  app in 40 lines. ಠ_ಠ

]]>
<![CDATA[Flash Realtime Graph using <pub>PubNub</pub>]]> http://www.pubnub.com/tutorial/flash-realtime-graph-using-pubnub-api
WANRING: This content is OLD!

Flash Realtime Graph using PubNub

PubNub messaging capabilities can be used on browser plug-ins like Flash and Silverlight. In this tutorial, we will see how to use PubNub Javascript API in Flash.

This experiment is very simple. We are going to develope a Graph in Flash that receives realtime updates.

Graph in Flash

Flash is one of the finest tool that is used to develope rich internet applications. In this experiment Flash is used to build a Graph that depicts the stock prices of some all time favourite shares listing on NYSE stock exchange. Data-source for this graph is an xml file. This Flash content is server through a web server.

The magic of PubNub Javascript API is to remotely attach a different xml to this graph that updates stock price on users browser. You can see the Graph in the image below.

PubNub is a messaging service on cloud. Messages can be published into a specific channel through a server and configure various clients listening to this channel.

In our case webpage that hosts the Flash chart is the client, listening to the stock updates flowing through a specific PubNub messaging channel using PubNub Javascript API.
You need to implement the following 3 steps to achieve this

Step 1: Include PubNub Javascript

	< script src="http://cdn.pubnub.com/pubnub-3.0.min.js"
	pub-key="demo"
	sub-key="demo"
	ssl="off"
	origin="pubsub.pubnub.com"
	id="pubnub"
	></script>
	

You need to have 2 keys namely - PUBLISH_KEY, SUBSCRIBE_KEY to include PubNub javascript as shown above.

Step 2:

Tune on to a specific channel and start listening to messages. Make a call to the "Subscribe(<Channel>, <Callback Method>)" method on PubNub API. You need to pass the 'Channel Name' and the 'Callback Method(delegate)' as parameters to this method as shown in the below snippet. This method starts listening on the specified channel continously. More details on the implementation of javascript API can be found in PubNub JavaScript API.

PUBNUB.subscribe()

	PUBNUB.subscribe({
		// Listen on channel 'my_channel' 
		channel: "my_channel1", 

		// Set Callback Function when Messages Received 
		callback: function (message) { 
		   UpdateChart(message); 
		}
	});

Step 3:

Now Need to implement the delegate method that will receive the xml feed to update the Flash chart.The implementation of the UpdateChart method is shown below.

	function UpdateChart(xmlFile) {
		thisMovie("FlashMovie").FlashUpdateChart(xmlFile); 
	}

Now lets implement a simple Server application. Server Application is going to be a .NET Windows based form.

Server Component

The role of the server here is very simple. It will publish messages into a specific channel. Lets call it a Messaging Server. You can see the Messaging Server in the image below.

There are two inputs, Channel Name & Content to broadcast. There is a button at the bottom, "BROADCAST" which will publish the message into the specified channel using PubNub C# API. Publishing the message using PubNub API is very simple. OnClick() of "BROADCAST" button is defined as in the code snippet below.

Publish()

	private void BroadCastOnClick()
	{
		pubnub = new Pubnub(PUBLISH_KEY, SUBSCRIBE_KEY, SECRET_KEY, false);
		string channel = txtChannel.Text;
		List<object> info = pubnub.publish(channel, comboBox1.Text);
		ShowStatus(info);
	}

Publishing messages involves 2 steps:

Step 1. Instantiate the PubNub API. You need to have 3 keys namely - PUBLISH_KEY, SUBSCRIBE_KEY & SECRET_KEY to instantiate PubNub API as in teh above code snippet. Grab your API Keys here.

Step 2. Make a call to the "Publish(<Channel>, <Message>)" method on PubNub API. You need to pass the 'Channel Name' and the 'Message to publish' as parameters to this method as shown in the above snippet. Your message is now published into the specified channel on Cloud. This method internally makes an HttpWebRequest to carryout the operation. More details on the implementation of Publish can be found in PubNub C# API.

In our case XML file names are published through the channel to update the graph.

Click here to download the source code for this solution.

Author:
Kris.Ram, Integration Specialist
Minnesota, USA

]]>
<![CDATA[HTML5 Desktop Notification Broadcasting]]> http://www.pubnub.com/blog/html5-desktop-notification-broadcasting

HTML5 Mass Broadcasting Desktop Notifications

Loading...

This tutorial explains how to broadcast desktop notifications to your users. PubNub has created a simple cross-browser utility to give you this ability with a few function calls. If your browser supports Native Desktop Notifications, such as Safari and Chrome, a message will appear outside of the web browser on your desktop. This is not trickery. It is a new feature included in HTML5.

Safari and Chrome will receive a popup outside of the web browser. For non WebKit browsers such as FireFox, Opera and IE an internal notification popup will appear. This approach works on Phones and Tablets too! Such as iPhone, Android and iPad.

Step 1: Include JavaScript

Add the following HTML block to your page. This gives you access to the PUBNUB.

<div
    channel-name=notifications-channel
    segregate-notifications-by-page=false
    id=desktop-notifications-config
></div>
<div id=pubnub pub-key=demo sub-key=demo></div>
<script src=http://cdn.pubnub.com/pubnub-3.1.min.js></script>
<script
src=http://www.pubnub.com/static/html5-desktop-notification-broadcasting.js
></script>

Step 2: Notify Ready

There are four functions you must know to enable desktop notifications. The first function is a utility method to test if a user is ready to receive desktop notifications. PUBNUB.notify.ready() will return a boolean of TRUE if the user is able to receive desktop notifications. If the return value is FALSE, then you must request permissions.

//
// User is Ready to Receive Desktop Notifications?
//
var allowed_desktop_notifications = PUBNUB.notify.ready();

The PUBNUB.notify.ready() will let you know if the user is able to receive desktop notifications. This function may return FALSE. If this is the case, then Step 3 will be necessary.

Step 3: Notify Enable

In case the response to PUBNUB.notify.ready() is FALSE, you may request to enable desktop notifications with the PUBNUB.notify.enable() function. This function will provide the user with an option to enable desktop notifications.

//
// Request Permissions to Receive Desktop Notifications
//
PUBNUB.notify.enable(function(){
    if (PUBNUB.notify.ready() {
        // User Accepted Permission
        // Ready to receive Desktop Notifications!
    }
    else {
        // User Denied Permission
        // User will not receive notifications.
    }
});

Step 4: Send Notification

The final step is to send the notification. This is accomplished by calling PUBNUB.notify() function. This function works like this:

//
// Send Notification
//
PUBNUB.notify({
    image : 'http://cdn.pubnub.com/assets/pubnub-70x70.png',
    title : 'PubNub Notification',
    body  : PUBNUB.$('broadcast-text').value || "empty message"
});

This will create a popup notification on your desktop. Make sure to test in the latest version of Chrome or Safari to get the Desktop Notification. Other browsers and mobile devices will fall back to an in-browser notification.

What if you wanted to push a desktop notification to your users from your web server or laptop using PHP, Ruby or Python?

//
// Send Desktop Notifications using PHP
//
require_once('Pubnub.php');
$pubnub = new Pubnub( $publish_key, $subscribe_key );
$info = $pubnub->publish(array(
    'channel' => 'notifications-channel',
    'message' => array(
        image => 'image.jpg',
        title => 'Title Text',
        body  => 'Content Body Text'
    )
));

Download PubNub PHP Push API

//
// Send Desktop Notifications using Python
//
from pubnub import Pubnub
pubnub = Pubnub( publish_key, subscribe_key, secret_key, ssl_on )
pubish_success = pubnub.publish({
    'channel' : 'notifications-channel',
    'message' : {
        'image' : "image.jpg",
        'title' : "Title Text",
        'body'  : "Content Body Text"
    }
})

Download PubNub Python Push API

//
// Send Desktop Notifications using Ruby
//
require 'Pubnub'
pubnub = Pubnub.new( publish_key, subscribe_key, secret_key, ssl_on )
info = pubnub.publish({
    'channel' => 'notifications-channel',
    'message' => {
        image => 'image.jpg',
        title => 'Title Text',
        body  => 'Content Body Text'
    }
})

Download PubNub Ruby Push API

There are lots of other languages that you may use to Push HTML5 Desktop Notifications with. Download them on PubNub's API at GitHub.

Notify Full Example

Here is a full example of the source code used in this example at the top of this page. You will see PUBNUB DOM utilities in use here to bind button click events.

<p>
    <button id=broadcast-enable class=broadcast-button>
        Enable Desktop Notifications
    </button>
    <span id=broadcast-ready>Loading...</span>
</p><p>
    <button id=broadcast-button class=broadcast-button>
        Broadcast HTML5 Desktop Notification
    </button>
    <input id=broadcast-text value='Hello Everyone!' />
</p>

<div
    channel-name=notifications-channel
    segregate-notifications-by-page=false
    id=desktop-notifications-config
></div>
<div id=pubnub pub-key=demo sub-key=demo></div>
<script src=http://cdn.pubnub.com/pubnub-3.1.min.js></script>
<script
src=http://www.pubnub.com/static/html5-desktop-notification-broadcasting.js
></script>
<script>(function(){
    function update_ready(enabled) {
        var ready = PUBNUB.$('broadcast-ready');

        if (enabled) {
            ready.innerHTML = 'Enabled';
            PUBNUB.attr( ready, 'class', 'broadcast-enabled' );
        }
        else {
            ready.innerHTML = 'Disabled';
            PUBNUB.attr( ready, 'class', 'broadcast-disabled' );
        }
    }

    update_ready(PUBNUB.notify.ready());

    PUBNUB.bind(
        'mousedown,touchstart',
        PUBNUB.$('broadcast-button'),
        function() {
            return PUBNUB.notify({
                image : 'http://cdn.pubnub.com/assets/pubnub-70x70.png',
                title : 'PubNub Notification',
                body  : PUBNUB.$('broadcast-text').value || "empty message"
            });
        }
    );

    PUBNUB.bind(
        'mousedown,touchstart',
        PUBNUB.$('broadcast-enable'),
        function() {
            PUBNUB.notify.enable(function(){
                update_ready(PUBNUB.notify.ready());
            });
        }
    );
})();</script>

That's it! Pretty simple yah? The heavy lifting is provided by PubNub. You may learn more about PubNub by Reading the Cloud-Hosted Service for Real-Time Messaging.

]]>
<![CDATA[Play Song ► Internet Programmer Heroes]]> http://www.pubnub.com/blog/internet-heroes-song-crockford-dahl-wall-torvalds-resig-souders

Internet Programmer Heroes Song

Just for you, PubNub has created an HTML5 Song Lyrics Animator using CSS3. To get you more excited, we had a song created featuring your favorite programmer heroes of the internet. Press the Space Bar on your Keyboard to progress the Lyrics one word at a time. We realized the importance of announcing the world's internet heroes. If you didn't know them before, now you will. This Game was created to educate you about the great Internet Heroes; the one's who shaped today's internet. Use Chrome, Firefox 4, Safari, IE9 or Opera10.

WARNING: Autoplay disables your ability to progress the lyris manually. It wont be as fun if you click "Autoplay" button. Instead, click the "Start Song" button. Then use the Lyrics Progression Key (Space bar). If you clicked Autoplay and want to try manual game mode, then Click "Reload" Button to try animating the lyrics yourself.

Don't click this until you have finished sync'ing your lyrics to the song. After you are done syncing the lyrics to the song with the "Next Word" button (or Space bar), click "Play Your Recording" to play back your lyric tracking. See how accurate you can get! This song is really hard to synchronize with lyrics unless you are a genius.

Click here to start the music. This is the starting point. Once the music starts, press your Space Bar to synchronize the music with the lyrics. Click the "Stop Song" button to reset your progress and start over. Your timing must be perfectly sync'ed to the Internet Heroes Song in order to be considered an awesome programmer. You may be pressing this Start/Stop button frequently.

Progress the lyrics by one word. Use this button to synchronize the lyrics to the song! After the song is over, click the "Play Your Recording" Button to see your accuracy.

Download Song Internet Programmer Heroes » MP3
Songs To Wear Pants To » Blog Archive » Internet Heroes
This one goes out to all our internet heroes people who deserve some recognition the people who made the net what it is today douglas crockford does nothing very well at yahoo in sunnyvale he's one of two people writing good JavaScript books the king of JavaScript is here all hail! you use node we all use node so big up to ryan dahl for his code and listen when our favorite autodidact audrey tang says "hug and embrace your internet trolls" ingy dot net so amazingly sweet man naked on stage he's the master of CPAN jonathan swartz what did he really do anyway? i don't really know but still i'm gonna say hey you're my internet hero oh oh you're my internet hero oh oh you're my internet hero oh oh you're my internet hero oh oh larry wall is the person who made all the versions of perl we've loved them since the very first but can we ask why is perl an onion? and by the way larry nice hawaiian shirt john resig is a programmer ninja he can't be beat he knows secret techniques and steve souders gave the web some speed so obviously we think that he's pretty neat jeremy zawodny he's got so many cats in so many places we don't know if he loves or hates sphinx and mysql but you'll see them pop up on craigslist james gosling you made the java HELL! you're my internet hero oh oh you're my internet hero oh oh you're my internet hero oh oh you're my internet hero oh oh igor sysoev give him respect 'cause PubNub uses nginx without you ruby on rails would be a wreck your free proxy software load balancer is the best rasmus lerdorf hmm let's see took a while to add closures to PHP and why no lexical scoping? we kids wanna here you say that it's not scope leakage and linus torvalds hey! he's the builder of the right way a force who's deserving of a cosmic bonus he created linux in case you didn't notice bjarne stroustrup i'm not impressed you created c++ out of bs guido van rossum thanks for the python more like van awesome maybe van right on who made ruby sexy? david hannson made ruby sexy who else made ruby sexy? yukihiro matsumoto made ruby sexy first it was called mocha livescript after brendan eich is the JavaScript origin master the apache group deserves a shootout: brian behlendorf roy t. fielding rob hartill david robinson cliff skolnick randy terbush robert s. thau and andrew wilson why are there so many of you? my apache group is just me and my mom jarrko hietaniemi is the master librarian though the cpan disclaimer no longer computes but those ruby gems outshine that and last but not least: joe armstrong, erlang woot! you're my internet hero oh oh you're my internet hero oh oh you're my internet hero oh oh you're my internet hero oh oh you're my internet hero oh oh you're my internet hero oh oh you're my internet hero oh oh you're my internet hero oh oh internet heroes we at PubNub want to thank you for making such a great internet PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub PubNub

This one goes out to all our internet heroes. People who deserve some recognition. The people who made the net what it is today.

Douglas Crockford - JavaScript Godfather

Douglas Crockford does nothing very well at Yahoo! in sunnyvale. He's one of two people writing good JavaScript books. The king of JavaScript is here - all hail!

Ryan Dahl - NodeJS Creator

You use node, we all use node so big up to Ryan Dahl for his code.

Audrey Tang - Haskell Perl6 Pugs

Listen when our favorite autodidact Audrey Tang says "Hug and Embrace your Internet Trolls".

Ingy dot Net - Perl CPAN Master

Ingy dot Net, so amazingly sweet man naked on stage he's the master of CPAN.

Jonathan Swartz - Perl Mason

Jonathan Swartz, what did he really do, anyway? I don't really know but still I'm gonna say.

Larry Wall - Perl Godfather

Larry Wall is the person who made all the versions of Perl, we've loved them since the very first but can we ask, why is Perl an Onion? and by the way, larry, nice Hawaiian Shirt.

John Resig - JavaScript Ninja

John Resig is a programmer ninja he can't be beat, he knows secret techniques.

Steve Souders - Speed Master

Steve Souders gave the web some speed so obviously we think that he's pretty neat.

Jeremy Zawodny - CraigsList - MySQL

Jeremy Zawodny, he's got so many cats in so many places we don't know if he loves or hates Sphinx and MySQL but you'll see them pop up on CraigsList.

James Gosling - Java Responsible

James Gosling, you made the Java HELL!

Igor Sysoev - NginX

Igor Sysoev, give him respect 'cause PubNub uses NginX. Without you Ruby on Rails would be a wreck. Your free proxy software load balancer is the best.

Rasmus Lerdorf - PHP

Rasmus Lerdorf, hmm let's see. Took a while to add closures to PHP. And why no lexical scoping? We kids wanna here you say that it's not scope leakage.

Linus Torvalds - Linux Kernel

Linus Torvalds, hey! He's the builder of the right way. A force who's deserving of a cosmic bonus. He created linux, in case you didn't notice.

Bjarne Stroustrup - C++ Responsible

Bjarne Stroustrup - I'm not impressed you created C++ out of BS.

Guido Van Rossum - Python Creator

Guido Van Rossum, thanks for the Python. More like Van Awesome, maybe Van Right On.

David Hannson - Ruby On Rails

Who made ruby sexy? David Hannson made ruby sexy.

Yukihiro Matsumoto

Who else made ruby sexy? Yukihiro Matsumoto made ruby sexy.

Brendan Eich

First it was called Mocha, LiveScript after. Brendan Eich is the JavaScript Origin Master.

The Apache Group

The Apache Group deserves a shootout: Brian Behlendorf, Roy T. Fielding, Rob Hartill, David Robinson, Cliff Skolnick, Randy Terbush, Robert S. Thau, and Andrew Wilson. Why are there so many of you? My Apache Group is just me and my mom.

Jarrko Hietaniemi

Jarrko Hietaniemi is the master librarian. Though the CPAN disclaimer no longer computes. But those Ruby gems outshine that.

Joe Armstrong

And last but not least: Joe Armstrong, Erlang woot! You're my Internet hero oh oh.

Internet Heroes

Internet Heroes, we at PubNub want to thank you for making such a great internet.

Download Song Internet Programmer Heroes » MP3
Songs To Wear Pants To » Blog Archive » Internet Heroes


]]>
<![CDATA[Play Song ► PubNub Bidirectional JSON Cloud-Hosted Service]]> http://bcove.me/w6aqmlzm Play Song ► PubNub Bidirectional JSON Cloud-Hosted Service]]> <![CDATA[Play Video ► Corona SDK Multiplayer Networking and Push Notifications API Tutorial]]> http://bcove.me/0vt2gysw Play Video ► Corona SDK Multiplayer Networking and Push Notifications API Tutorial]]> <![CDATA[PubNub 3.1 API Released]]> http://www.pubnub.com/#pubnub-3.1-api PubNub 3.1 API Released]]> <![CDATA[Multiplayer Networking API for iPhone Corona SDK Games]]> http://www.pubnub.com/game/multiplayer-gaming-iphone-lua-corona-sdk

Corona SDK Multiplayer Networking API for Mobile Games

Enable Multiplayer Networking with your Mobile Games with 3 functions.

  1. Init PubNub Multiplayer Object
  2. Call Subscribe() to begin receiving messages.
  3. Call Publish() to send messages.

Click here to visit Corona SDK Website:

Download Corona Multiplayer API

Download Source Code here: https://github.com/pubnub/pubnub-api/tree/master/lua-corona

Follow these easy steps to get starting with your Multiplayer API.

  1. Download Lua Corona Multiplayer API
  2. Get Your PubNub Keys Here
  3. Copy the files into your Lua Code Directory
  4. Continue Reading to add just 3 functions to Enable Multiplayer Support.

Get Your PubNub Keys Here

http://www.pubnub.com/account#api-keys

Learn about PubNub Cloud-Hosted Service for Real-Time Messaging

http://www.pubnub.com PubNub is a new kind of Cloud-Hosted Broadcasting Service for Mass Communication on Mobile Phones, Tablets, TVs, HTML5 Web Browsers and Game Consoles. Already more messages are published to PubNub each day than to Twitter. We believe in unified broadcasting and mass communication empowerment for application and game developers who build on Mobile Phones, TVs, HTML5 Web Browsers, Tablets and Game Consoles.


PubNub Creates Real-time Social Experiences

Initiate Multiplayer PubNub Object.

1
2
3
4
5
6
7
8
9
10
11
12
13
require "pubnub" 
 
-- 
-- GET YOUR PUBNUB KEYS HERE: 
-- http://www.pubnub.com/account#api-keys 
-- 
multiplayer = pubnub.new({ 
    publish_key   = "demo",             -- YOUR PUBLISH KEY 
    subscribe_key = "demo",             -- YOUR SUBSCRIBE KEY 
    secret_key    = nil,                -- YOUR SECRET KEY 
    ssl           = nil,                -- ENABLE SSL? 
    origin        = "pubsub.pubnub.com" -- PUBNUB CLOUD ORIGIN 
})

Listen for Messages from Other Players.

1
2
3
4
5
6
7
8
9
10
11
12
13
-- 
-- PUBNUB SUBSCRIBE CHANNEL (RECEIVE MESSAGES) 
-- 
multiplayer:subscribe({ 
    channel  = "lua-corona-demo-channel",
    callback = function(message) 
        -- MESSAGE RECEIVED!!! 
        print(message) 
    end,
    errorback = function() 
        print("Network Connection Lost") 
    end 
})

Send Message To Other Players.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
-- 
-- PUBNUB PUBLISH MESSAGE (SEND A MESSAGE) 
-- 
multiplayer:publish({ 
    channel  = "lua-corona-demo-channel",
    message  = { "1234", 2, 3, 4 },
    callback = function(info) 
 
        -- WAS MESSAGE DELIVERED? 
        if info[1] then 
            print("MESSAGE DELIVERED SUCCESSFULLY!") 
        else 
            print("MESSAGE FAILED BECAUSE -> " .. info[2]) 
        end 
 
    end 
})

Stop Listening for Messages.

1
2
3
4
5
6
-- 
-- PUBNUB UN-SUBSCRIBE CHANNEL (STOP RECEIVING MESSAGES) 
-- 
multiplayer:unsubscribe({ 
    channel = "lua-corona-demo-channel" 
})


Multiplayer Netowrking Mobile Game Foundation for Corona SDK

Load Message History

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
-- 
-- PUBNUB LOAD MESSAGE HISTORY 
-- 
multiplayer:history({ 
    channel  = "lua-corona-demo-channel",
    limit    = 10,
    callback = function(messages) 
        if not messages then 
            return print("ERROR LOADING HISTORY") 
        end 
 
        -- NO HISTORY? 
        if not (#messages > 0) then 
            return print("NO HISTORY YET") 
        end 
 
        -- LOOP THROUGH MESSAGE HISTORY 
        for i, message in ipairs(messages) do 
            print(Json.Encode(message)) 
        end 
    end 
})

Get PubNub Server Time

1
2
3
4
5
6
7
8
9
-- 
-- PUBNUB SERVER TIME 
-- 
multiplayer:time({ 
    callback = function(time) 
        -- PRINT TIME 
        print("PUBNUB SERVER TIME: " .. time) 
    end 
})


PubNub High Scale Cloud-Hosted Real-time Messaging Service

]]>
<![CDATA[Tutorial: How To Build HTML5 Multiplayer Game Foundation]]> http://www.pubnub.com/game/html5-multiplayer

Check out the NEW! Corona Multiplayer Networking SDK to build Real-time Games on Mobile Phones iPhone.

Tutorial: How To Build HTML5 Multiplayer Game Foundation

This is an HTML5 Multiplayer Game Tutorial. This page is the foundation for creating your own Monetizable HTML5 games and applications with Live Data Streaming. You will learn how to create a game and earn money from internet game players. Use PubNub to engage your players with your HTML5 Multiplayer and Flash Games. The PubNub Game below is a completed game demonstrating the Power of PubNub HTML5 Gaming and Monetization.

Check out the new Corona Multiplayer Networking SDK to build Real-time Games on Mobile Phones iPhone.

PubNub Tutorial: How To Build HTML5 Multiplayer Game Foundation

If you are here to learn how to make a Multiplayer Game, continue reading! If you are here to play the HTML5 Multiplayer Game to Earn Credits and Increase Your Customer Level, then go play the game! The information below explains how to create your own HTML5 Multiplayer Games and earn money from players.

The HTML5 Multiplayer Game is best played on Google Chrome, FireFox 4, Safari and Mobile Safari. Other browser will work, however CSS3 animations will not render. A simple User Interface will be displayed if you are not running an HTML5 browser.

Loading...
{message}
Clear Countdown
1 Token
Level Loading...
Loading... Tokens
Loading... Credits
Post Comment
{name}: {message}
{name}: {message}
? New Players
? Purchased
? Payments
★ LEVEL UP!!! ★
★ YOU ROCK ★
TOKENS
ACQUIRED
close [x]
Purchase PubNub Tokens
Your timer is taking too long to reach ZERO? Buy Tokens! Use a Token to keep playing. Buy tokens to support PubNub.

You must Be Logged to Get Tokens!

Cancel.

PubNub Message Credits

Message Credits are won as you play the HTML5 Multiplayer Game. These are freebee credits which you normally pay for by enabling billing on your account. PubNub is a Cloud-Hosted Service for HTML5 Data Streaming, and much more. You are able to use your Message Credits for the PubNub Cloud-Hosted Service. Message Credits are used to stream data to your players.

The HTML5 Multiplayer Game above is tied to your PubNub Account. When you win credits in the game, you are incrementing your account balance! Use your credits towards the PubNub Cloud-Hosted Service for Real-Time Messaging powering the multiplayer games you build. To ensure your account is billable and stays active beyond the free quota and beyond the credits you won by playing the HTML5 Game, you must enable billing on your account.

So how does it work? When a player clicks the Play Button, a message is sent to the PubNub Cloud. This message is intended to be broadcast to everyone playing the HTML5 Multiplayer Game. PubNub provides this vital community connection. Learn more about the PubNub Cloud-Hosted Service for Real-time Messaging and Broadcasting Here.

Payments Display Ticker

Enhance the sense of community by displaying the total dollar contribution provided by the player's. This is demonstrated in the HTML5 Multiplayer Game above where the dollar amount is highlighted in green. Offering this information provides entertainment and engages players on an analytic level. You can think of these numbers as Real-time Analytics.

PubNub provides Live Data Streaming which enables applications such as Real-time Analytics. The first step in creating a Live Data Stream is to setup a PUBNUB.subscribe() channel on the mobile phone or web browser.

// RECEIVE MESSAGES
PUBNUB.subscribe({
    channel  : 'my-game-channel',
    callback : function(message) {

        // A message is received here and it contains
        // the information from the original publish.
        // With this hook, you update the Player UI.
        // The message in this case contains information that
        // a new purchase has been placed.
        // You take this advantage to update
        // the HTML interface with the new balance.

    }
});

Get your PUBNUB JavaScript Include Here.

The code above demonstrates the simplicity of the PubNub Data Streaming Cloud API. Calling PUBNUB.subscribe() is the first step of two. The Subscribe Function will wait and listing for a message to be sent accros the network. A message is sent by calling Publish function. The next step is calling PUBNUB.publish() to send messages to the subscribers.

// SEND A MESSAGE with JavaScript
PUBNUB.publish({
    channel : 'my-game-channel',
    message : {

        // You broadcast the total purchase dollar amount.
        // Everyone will receive this message via PUBNUB.subscribe()

        total_purchases : '$1,200.00'
    }
});
Data Streaming is easy with PubNub. This engages your game players with Live, Real-time Data provided by PubNub's Mass Broadcasting Capabilities. Note that you may send a message from every location including Mobile Phones (iPhone, Android), Web Servers (Apache, Tomcat and NginX), Web Browsers (FireFox, Chrome, Internet Explorer), your laptop and more. The following is an example of publishing messages on multiple platforms and languages:
// SEND A MESSAGE with Lua Corona SDK
multiplayer:publish({
    channel  = "lua-corona-demo-channel",
    message  = { "1234", 2, 3, 4 }
})
Get your Publish and Subscribe Keys Here.
Download PubNub Lua Corona Multiplayer API
Learn how to Receive Messages with Lua Corona SDK
// SEND A MESSAGE with Objective-C
Pubnub *pubnub = [[Pubnub alloc]
    publishKey:   @"publish_key"
    subscribeKey: @"subscribe_key"
    secretKey:    @"secret_key"
    sslOn:        NO
    origin:       @"pubsub.pubnub.com"
];
[pubnub
    publish: @"my-game-channel"
    message: [NSDictionary
        dictionaryWithObjectsAndKeys:
        @"total_purchases", @"$1,200.00", 
    nil]
    deligate: [Response alloc]
];
Get your Publish and Subscribe Keys Here.
Download PubNub Objective-C
Learn how to Receive Messages with Objective-C
// SEND A MESSAGE with RUBY
pubnub = Pubnub.new( 'publish_key', 'subscribe_key' )
pubnub.publish({
    'channel' => 'my-game-channel',
    'message' => { 'total_purchases' => '$1,200.00' }
})
Get your Publish and Subscribe Keys Here.
Download PubNub Ruby
Learn how to Receive Messages with Ruby
// SEND A MESSAGE with PHP
$pubnub = new Pubnub( 'publish_key', 'subscribe_key' );
$pubnub->publish(array(
    'channel' => 'my-game-channel',
    'message' => array( 'total_purchases' => '$1,200.00' )
));
Get your Publish and Subscribe Keys Here.
Download PubNub PHP
Learn how to Receive Messages with PHP
// SEND A MESSAGE with Python
pubnub = Pubnub( 'publish_key', 'subscribe_key' )
pubnub.publish({
    'channel' : 'my-game-channel',
    'message' : { 'total_purchases' : '$1,200.00' }
})
Get your Publish and Subscribe Keys Here.
Download PubNub Python
Learn how to Receive Messages with Python
// SEND A MESSAGE with Perl
my $pubnub = Pubnub->new( 'publish_key', 'subscribe_key' );
$p->publish( {
    channel => 'my-game-channel',
    message => { 'total_purchases' => '$1,200.00' }
}),
Get your Publish and Subscribe Keys Here.
Download PubNub Perl5
Learn how to Receive Messages with Perl
// SEND A MESSAGE with .NET C#
Pubnub pubnub = new Pubnub( "publish_key", "subscribe_key" );
Dictionary<string,string> message = new Dictionary<string,string>();
message.Add( "total_purchases", "$1,200.00" );
pubnub.publish( channel, message );
Get your Publish and Subscribe Keys Here.
Download PubNub .NET C#
Learn how to Receive Messages with .NET C#
// SEND A MESSAGE with Java
Pubnub pubnub  = new Pubnub( "publish_key", "subscribe_key" );
JSONObject message = new JSONObject();
try { message.put( "total_purchases", "$1,200.00" ); }
catch (org.json.JSONException jsonError) {}
JSONArray info = pubnub.publish( 'my-game-channel', message );
Get your Publish and Subscribe Keys Here.
Download PubNub Java
Learn how to Receive Messages with Java

If you have trouble getting started, visit the PubNub forums at The GitHub Issue Center. Search for you answer first, if you don't find it submit a new issue.

Payment Model

Virtual Currency provides a medium for extended playability for the player. This allows the player to engage the game longer and provide value to the online community. To broaden your target audience, make sure to offer game upgrades as an optional experience. Additional areas may be introduced offering extra gameplay. In the case of the PubNub HTML5 Multiplayer Game, the players are able to advance their account quickly, allowing faster credit accumulation. With a higher player level, higher scores are achievable.

CSS3 Animations with HTML5

Motion gameplay and good looking aesthetics are achievable with CSS3. If your web browser supports CSS3 Animations, then the HTML5 Multiplayer Game on this page will render them! CSS3 Animation is supremely simple to implement. Start by defining a normal CSS Selector followed by some JavaScript:

<-- STEP 1 of 4: CSS3  -->
<style>
    #my-element-div {
        cursor: pointer;
        background: #f90;
        color: #fff;

        /* Specify that this element will animate
        for 0.8 seconds if changes are
        made via JavaScript. */
        transition: all 0.8s;
        -o-transition: all 0.8s;
        -moz-transition: all 0.8s;
        -webkit-transition: all 0.8s;
    }
</style>

<-- STEP 2 of 4: HTML Div Element -->
<div id=my-element-div>CLICK THIS TEXT!!!</div>

<-- STEP 3 of 4: PUBNUB JavaScript -->
<div>
    pub-key="demo"
    sub-key="demo"
    ssl="off"
    origin="pubsub.pubnub.com"
    id="pubnub"
</div>
<script src="http://cdn.pubnub.com/pubnub-3.1.min.js"></script>

<-- STEP 4 of 4: Applicatoin Logic -->
<script>(function(){
    var my_element_div = PUBNUB.$('my-element-div');
    PUBNUB.bind( 'mousedown,touchstart', my_element_div, function() {
        if (PUBNUB.attr( my_element_div, 'clicked' ) != 'yup!') {
            PUBNUB.attr( my_element_div, 'clicked', 'yup!' );
            PUBNUB.css( my_element_div, {
                color           : '#f90',
                backgroundColor : '#fff'
            } );
        }
        else {
            PUBNUB.attr( my_element_div, 'clicked', ' ' );
            PUBNUB.css( my_element_div, {
                color           : '#fff',
                backgroundColor : '#f90'
            } );
        }
    } );
})();</script>

CLICK THIS TEXT!!!

Get your PUBNUB JavaScript Include Here.

If your web browser does not support CSS3 Animations, then the div will toggle without a transition. However if you are running Chrome, Safari, Mobile Safari, FireFox 4 or Opera then you will see a smooth transition of colors. You must do the following to achieve CSS3 Transitions:

  1. Set up a style sheet defining your element and animation properties.
  2. Add the HTML <div> element.
  3. Include your PUBNUB JavaScript API.
  4. Add JavaScript to toggle display properties of the <div> element.

Animations indicates that happening is happening in the game and provides a moment of time for the player to react. Smooth animated motions are detectable and intriguing to the human eye. Use CSS3 animations to engage your users playing your games and using your application. Animations enhance every User Interface experience including Games, Analytics, Messaging and more.

JSONP Request Foundation

JSONP works everywhere. From this point on, use only JSONP. Drop AJAX XHR (XML HTTP Request). There are no limitations to JSONP and is therefore recommended as your data transport choice. JSONP is simple to implement and light weight with many invisible benefits which make application building great. The following code is the function to issue a JSONP request:

/*
    USAGE EXAMPLE:
    request(
        '/player-status',         // URL
        { 'key' : 'val' },        // JSON PARAMATERS
        function(response){ ... } // CALLBACK FUNCTION
    );
*/
var NOW = 1;
function request( url, data, callback ) {
    var jsonp = PUBNUB.create('script')
    ,   uni   = 't'+(NOW++)+(+new Date);

    window[uni]      = callback || function(){};
    data['callback'] = uni;
    jsonp.src        = url + '?data=' + escape(JSON.stringify(data));

    PUBNUB.search('body')[0].appendChild(jsonp);
}
The PubNub HTML5 Multiplayer Game uses JSONP to call Google App Engine to communication player activity. JSONP is compatible with every application server including Apache, NginX, Tomcat and more. In the HTML5 Multiplayer Game, the JSONP request function is called when you click the "Play!" button.
request(
    '/click',
    { click : 1 },
    function(response){
        // The "response" var contains information
        // from the applicatoin server.
        console.log(response);
    }
);
The code above is called when you click the "Play!" button. When this happens the request() function issues a request to the following URL:
/*
    Request:
    /click?data={"click":1,"callback":"t123456"}

    Encoded Request:
    /click?data=%7B%22click%22%3A1%2C%22callback%22%3A%22t123456%22%7D

    The request must be encoded.
    Calling the request(...) function does this for you.
*/
Note that the request data is encoded and must be decoded by the server in order to process the request. There is an additional detail needed on the server in order to respond with the correct information:
def jsonp_response( web, response ):
    ## Get the Data URL Varaible
    request  = json.loads(urllib.unquote(web.request.get( 'data', '' )))
    ## Extract the Callback
    callback = request['callback']

    ## Set Appropriate Header for JSONP
    web.response.headers["Content-Type"]  = 'text/javascript'
    web.response.headers["Cache-Control"] = 'no-cache'

    ## Respond with Padded JSON
    web.response.out.write(callback + '(' + json.dumps(response) + ')')
The code above is written in python using a common WSGI control pattern. The "data" URL variable is extracted, URL decoded and JSON decoded. The "callback" variable is extracted to provide the JSON Padding. The result of this request looks like this:
t123456({"message":"You lost a gear and a few bolts","credits":-10})
This can be done with every web server. Python is used here for simplicity. Important details for the server are:
  1. Receive request from Client and decode URL Variables including the "callback" wrapper "t123456".
  2. Set the "Content-Type" and "Cache-Control" headers.
  3. Respond with JSON wrapped with the "callback" ("t123456").
That's it! You now have the recipe to create JSONP requests.

Streaming Keystroke Chat

Exceed the expectations of your players by offering PubNub Instant Keystroke Chat experience. Quickly deliver the experience to your players providing "Instant Gratification". Since the "Play!" button has a timer associated with it, you need to keep your players active by offering a community chat interface.

PubNub makes streaming data easy and instant. Streaming Keystroke Chat hooks on the Keydown Event. When you press a key on your keyboard, an event is fired. A hook is placed into this keystroke event and used to publish a message of the typed text. To prevent data overload on the client stream, you must wrap the Keystroke Event in a Delayed Callback. This provides an improved usability experience for end users as the User Interface is redrawn with locking. The following code provides the foundation for creating a stream of data based on Keyboard Events (and Virtual Keyboard Events on Mobile Phones/Tablets).

PUBNUB.bind( 'keydown', chat_input, function(e) {
    // Did the user press the ENTER KEY?
    if (e.keyCode == 13) return new_chat_line();

    // Send Message
    // (What you typed so far)
    send_keystroke();

    // Very Important to Return True
    // This allows the keyup event to fire.
    return true;
} );

To prevent User Interface Locking, you must rate limit keystroke publishes to 3 or 4 per second. Otherwise the interface will lock causing unpleasant typing experiences. Also you are recommended to rate limit the message delivery to prevent rapid PubNub Message Credit Drain.

// Create an Updater Function
// This provides a rate limited interface
// to Events; such as the KeyDown Event.
var send_keystroke = updater( function() {

    // You add a Timeout to allow the DOM
    // to update every keystroke
    // before the message is published.
    setTimeout( function() {

        // Publish The Message, even
        // if the message is incomplete.
        publish_comment();
    }, 10 );
}, 150 );
// Here is the updater() function.
function updater( fun, rate ) {
    var timeout
    ,   now     = function(){return+new Date}
    ,   last    = 0
    ,   runnit  = function() {
        var right_now = now();

        if (last + rate > right_now) {
            clearTimeout(timeout);
            timeout = setTimeout( runnit, rate );
        }
        else {
            last = now();
            fun();
        }

        return true;
    };

    return runnit;
}
Now you have a rate limited function which may be called thousands of times per second, yet only triggers the event 3 to 4 times per second. This triggers your function to send the must up-to-date message at a reasonable rate. Next let's take a look inside the publish_comment() function to see what is happening.
// Trim White Space
var trim_rx        = /^\s*|\s*$/g
// Chat Message ID
,   chat_box_count = +new Date()
// Prevent Displaying Bad Characters and Scripts
,   safe_rx        = /[\r\n<>]/g;

// Post Comment
function publish_comment() {
    // Prevent Publishing Empty Messages
    if (!chat_input.value.replace( trim_rx, '' )) return;

    // If the player isn't ready, don't send.
    // We need the Player's name for example.
    if (!player.ready) return;

    // Send a network Broadcast using PubNub.
    PUBNUB.publish({
        channel : 'my-game-channel',
        message : {
            action : 'chat',

            // Player Details (name, public_id, etc)
            player : player,

            // Only allow 200 Character Messages.
            // Truncate anything longer.
            text   : chat_input.value.slice(-200).replace( safe_rx, '' ),

            // Each player will have multiple
            // chat lines during gameplay.
            // When you press the Enter Key, a new
            // chat line is generated and the next
            // ChatBox is displayed on a new line.
            // This allows you to send updates
            // to the current line of text.
            box_id : player.info.uuid + '-' + chat_box_count,

            // This is a very important concept
            // with real-time messaging.
            // Messages in the cloud are
            // not always delivered in order
            // due its asynchronous nature.
            // Therefore you must associate a
            // timeline to track
            // message order.
            last   : ++chat_publishes
        }
    });
}

// Setup the Subscribe Callback
PUBNUB.subscribe({
    channel  : 'my-game-channel',
    callback : function(message) {
        // Capture UUID (the Public ID of a Player)
        var uuid = 'uuid' in message && message.uuid ||
            'player' in message && message.player.info.uuid;

        // Is this a new Player?
        if (!players.get(uuid)) {
            players.add(uuid);
        }

        // Render the Message on Screen
        receive_comment(message);
    }
});
These are the important parts when you create a Real-time Keystroke Chat. Note there is a portion of UI logic left undiscussed as that is up to you to decide how this should look. The most important part is for you to rate limit the event bindings to provide a responsive user interface.

Security Implementation

Application security comes in several layers include: Client Logic, Server Logic, Transport Encoding, SSL Encryption, Message Signing and Access Levels. The HTML5 Multiplayer Game uses Client and Server Logic to provide a layer of security around data tracking for credits and tokens. For example, you are required to log in with your Google account to send authenticated requests; like the "Play!" button. These requests are for interaction related to tokens and credit currency.

Additionally, logic is implemented in the JavaScript to provide an improved user experience; preventing script injection. For example, if you change your player name during the game, you are limited by 10 to 20 characters maximum. This logic is implemented in the JavaScript on every client. This means if a hacker were to attempt to deliver a name longer than 20 characters, then truncation occurs on the client system. Therefore the hacker is not able to affect other players.

Further layers of Security are available with the PubNub Cloud-Hosted Service. SSL Encryption is an industry standard for keeping messages secret. Because of the High CPU cost, encrypted messages are more expensive, and totally optional. PubNub counts SSL Encrypted messages as double. Learn more about PubNub Pricing here.

Message Signing is a process of including a hashed value with the published message. The hashed value is calculated by the sum characters of the request string with the addition of your account's Secrete Key. You can find your secret key here. Message Signing provides additional insurance confirming the origin of the message to be authentic.

The last security implementation is the most popular and most recommended. This process involves removing the Publish Key from your JavaScript. This prevents hackers from sending messages. You can accomplish this security method by deleting the reference to the Publish Key in your JavaScript Include. You can find your JavaScript Include here. Remove the line that looks like this:

<div
    pub-key="PUBLISH_KEY" REMOVE THIS LINE
    sub-key="demo"
    ssl="off"
    origin="pubsub.pubnub.com"
    id="pubnub"></div>
<script src="http://cdn.pubnub.com/pubnub-3.1.min.js"></script>
By hiding the publish key, you prevent everyone from sending messages except yourself. This means the PUBNUB.publish() function will no longer work. Now you must use one of the Server APIs located here to send your messages securely.

Monetization

There are gracious consumers who will support your applications and games thru purchases. However you must offer them a way to give you money! You must setup an interface which accepts multiple payment options. This has been traditionally time consuming to setup. Not anymore! Use Social Gold to quickly setup your payment gateway. Offer every payment option to allow players to give you money. You must provide a way for your players to submit payments.

After players submit a payment, you may provide enhanced or continued gameplay. The PubNub HTML5 Multiplayer Game extends gameplay by reseting the game timer. This gives you the opportunity to continue playing and increase your Customer Level Quickly. You are a happy player!

HTML5 Game Compatibility

This page is totally compatible with every web browser, mobile phone and tablet device. iPhone, iPad, Android, Samsung Galaxy, Android, FireFox, Google Chrome, Internet Explorer, Safari, Mobile Safari and more!

We ♥ Developers

We love developers. Here are resources for you, the developer, to allow you to build amazing HTML5 Multiplayer Games and Applications:

]]> <![CDATA[System Admins. R.I.P.?]]> http://blogs.mulesoft.org/system-admins-r-i-p/ System Admins. R.I.P.?]]> <![CDATA[Play Video ► Perl 5 <pub>PubNub</pub> Screen Cast Tutorial]]> http://bcove.me/8qz4y6ci Play Video ► Perl 5 PubNub Screen Cast Tutorial]]> <![CDATA[Play Song ► Stephen Blum, Founder of <pub>PubNub</pub>, is The Awesome Programmer]]> http://www.pubnub.com/blog/stephen-blum-founder-of-pubnub-is-the-awesome-programmer

Founder of PubNub is The Awesome Programmer

January 15th, 2011

Play Song

About Founder of PubNub

Stephen Blum Founder of PubNub My name is Stephen Blum, founder of PubNub Cloud-Hosted Service providing Real-Time Messaging to Mobile Phones, TVs, Computers, Game Consoles and Tablets. Already more messages are published to PubNub each day than to Twitter. I moved to the much sunnier San Francisco in early 2009 from Seattle. With the rich knowledge of the SF townspeople, great tech is easy to grow. PubNub is a product of a common need in social applications; Push Notifications. We provide simple Push Notifications for Web and Mobile Games on iPhone, Android, Palm, Blackberry, Windows Mobile, WebOS, Laptops, Computers, Web Browsers and more! I'm excited about the technical and the cutting edge. I founded my first company in Seattle Washington in 2005 selling a first of its kind front-end Real-time CMS LTSun. My company was acquired in 2007. I am contributing new tech for the next great web with PubNub.

Stephen Blum Founder of PubNub and Creator of NodeJuice NodeJuice and VIM are included in my daily development tool set. NodeJuice is a tool which allows you to develop with a push connection to your web browser. Automatic browser refresh on file change or update is what you can call it. Develop on one to many browsers simultaneously without needing to reload manually.

Stephen Blum Founder of PubNub uses VIM I take advantage of powerful languages and design patterns such as Real-time, Evented I/O, JavaScript, Perl 5 and Perl 6, Python, C, Ruby, PHP, Erlang and Haskell. This juice has been squeezed into PubNub, making adoption super easy by providing two function calls, Publish() and Subscribe() for all platforms and languages.

Song Lyrics: "Stephen Blum Founder of PubNub is The Awesome Programmer"

You are wrong! Stephen Blum's awesomeness will stab you in the face. Uh. The killer programmer. Code slammer. So glamour. Folks clamor. Oh man, you're taking over this whole place. Author of the first non-traditional trans-dimensional elevators, don't press up now boy. Stephen Blum - Legend of Master Programming, all you kiddies better make some noise! Stephen is the awesome Now you rock 'cause you know the best programmer. Stephen is the awesome. All you oblongs talking slant about Stephen Blum are wrong - he loves you.

]]>
<![CDATA[NthCaller by Tim Lytle Wins Twilio "Push" Developer Contest!]]> http://blog.twilio.com/2011/01/nthcaller-by-tim-lytle-wins-twilio-push-developer-contest.html NthCaller by Tim Lytle Wins Twilio "Push" Developer Contest!]]> <![CDATA[Client/Server Model using .NET C# API]]> http://www.pubnub.com/tutorial/csharp-client-server-model-api
WANRING: This content is OLD!

Client/Server Model using .NET C# API

PubNub provides strong capabilities to write Client-Server applications using its highly flexible and scalable Publish and Subscribe implementation.

This article describes a basic client/Server implementation using the PubNub C# API. We will see how a Server can push messages into a channel and how Clients stay tuned to receive messages from Server. This is a completely .NET solution presenting the messaging techniques of PubNub to build a Client/Server model. We will first look at what is a Server in our experiment and go through the steps to build it. After that we will see how to build a client.

Server Component

The role of the server here is very simple. It will publish messages into a specific channel. Lets call it a Messaging Server. You can see the Messaging Server in the image below.

There are two inputs, Channel Name & Content to broadcast. There is a button at the bottom, "BROADCAST" which will publish the message into the specified channel using PubNub C# API.

Publishing the message using PubNub API is very simple. OnClick() of "BROADCAST" button is defined as in the code snippet below.

Publish()

	private void BroadCastOnClick()
	{
		pubnub = new Pubnub(PUBLISH_KEY, SUBSCRIBE_KEY, SECRET_KEY, false);
		string channel = txtChannel.Text;
		List<object> info = pubnub.publish(channel, richTextBox1.Text);
		ShowStatus(info);
	}

Publishing messages involves 2 steps:

Step 1. Instantiate the PubNub API. You need to have 3 keys namely - PUBLISH_KEY, SUBSCRIBE_KEY & SECRET_KEY to instantiate PubNub API as in the above code snippet.

Grab your API Keys here.

Step 2. Make a call to the "Publish(<Channel>, <Message>)" method on PubNub API. You need to pass the 'Channel Name' and the 'Message to publish' as parameters to this method as shown in the above snippet. Your message is now published into the specified channel on Cloud. This method internally makes an HttpWebRequest to carryout the operation. More details on the implementation of Publish can be found in PubNub C# API.

Client Component

Server publishes messages. So, eventually our client should listen to messages. How does this clinet look like? Youc an see the Subscribing client component in the image below.

There is only one input required to subscribe for messages, Channel Name. There is a button at the top, "START SUBSCRIPTION" which will tune client into the specified Channel and start listening to the messages on that Channel using PubNub C# API.

As and when a message is published from the server on this channel, client grabs it immediately and displays it on the text box.

The OnClick() of "START SUBSCRIPTION" button is defined in the code snippet below.

StartSubscriptionOnClick()

	private void StartSubscriptionOnClick(object sender, EventArgs e)
	{
		pubnub = new Pubnub(PUBLISH_KEY, SUBSCRIBE_KEY, SECRET_KEY, false);

		channel = txtChannel.Text;

		// Extract History on successful Connection
		List<object< history = pubnub.history(channel, 10);
		ExtractHistory(history);

		// Listen to the channel and update the UI
		this.backgroundWorker1.RunWorkerAsync();
	}

Subscribing for messages requires 3 steps:

Step 1. Instantiate the PubNub API. You need to have 3 keys namely - PUBLISH_KEY, SUBSCRIBE_KEY & SECRET_KEY to instantiate PubNub API as in teh above code snippet.

Grab your API Keys here.

Step 2. Retrieve History of messages. Make a call to the "History(<Channel>, <No. of past messsages>)" method on PubNub API. You need to pass the 'Channel Name' and the 'No. of past messsages' as parameters to this method as shown in the above snippet. You can see the History messages retrieved in the image of the Client.

Step 3. Tune on to a specific channel and start listening to messages. Make a call to the "Subscribe(<Channel>, <Callback Method>)" method on PubNub API. You need to pass the 'Channel Name' and the 'Callback Method(delegate)' as parameters to this method as shown in the below snippet.

This method starts listening on the specified channel continously. So, it is executed on a separate background thread as shown in the above snippet - "this.backgroundWorker1.RunWorkerAsync();".

Subscribe()

	private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
	{
		pubnub.subscribe(channel, new Pubnub.Procedure(SubscriptionUpdates));
	}

History & Subscribe methods internally makes an HttpWebRequest to carryout the operation. More details on the implementation of these methods can be found in PubNub C# API. There can be multiple clinets listening to the same channel or different channels where the server will publish the messages.

Click here to download the source code for this solution.

Author:
Kris.Ram, Integration Specialist
Minnesota, USA

]]>
<![CDATA[Fast, Free, Real-time Chat]]> http://www.virtualworldscommunity.com/showthread.php?249-Fast-free-real-time-chat&s=b3c5d03d9a88fdc91822b2a20ff854ce Fast, Free, Real-time Chat]]> <![CDATA[Introducing PubNub - The New Cloud-Hosted Service for Real-time Messaging]]> http://www.ifc0nfig.com/introducing-pubnub-the-new-cloud-hosted-service-for-real-time-messaging/ Introducing PubNub - The New Cloud-Hosted Service for Real-time Messaging]]> <![CDATA[PubNub contributed $700 to HumbleBundle]]> http://twitter.com/NgoMinhNam/status/14910222908792833 PubNub contributed $700 to HumbleBundle]]> <![CDATA[Analyzing the Humble Indie Bundle 2 After a Single Day]]> http://www.diygamer.com/2010/12/analyzing-humble-indie-bundle-2-single-day/ Analyzing the Humble Indie Bundle 2 After a Single Day]]> <![CDATA[Harmful Google Search Suggest]]> http://www.pubnub.com/blog/harmful-google-search-suggest

Harmful Google Search Suggest

November 23rd, 2010 Google Search is suggesting to people that they made a mistake. Even though their original search was accurate, Google Search will recommend an internal Google Product rather than the original search. This is harmful to our business. We love Google at PubNub. When we type our company name into Google Search and see this, it is bad for business.

Harmful Google Search Suggest

The image above shows PubNub's very active web presence. Almost every search result is related to PubNub. When our company name is typed into Google search, it is flooded with inaccurate suggestions that defer potential customers to the wrong place.

Harmful iPhone Google Search

Harmful iPhone Google Search Suggest

Harmful Google Search Suggestions exists on the iPhone too. Notice how every suggestion in the list points to the wrong place. This is harmful to our business. We are not the only company affected by this.

Google Search Suggestion is a useful feature. We use this feature often and rely on it for corrections; mostly spelling corrections. Typos are frequent, and this corrective suggestion process is often a daily spelling joy. However it is bad to lose customers when the Google Suggestion process drives away the originally intended search.

Most Harmful Google Search

Most Harmful Google Search Suggest

This is the most harmful search suggestion scenario. Notice that every effort by Google Search is placed on driving traffic away from the originally intended search term. Each search result is unrelated to the PubNub search term.

Could this be an issue with Google Instant Search? We recommend trying this with your company's name to make sure a similar problem does not exist. Test with as many devices and web browsers as you have available to you.

Harmful Bias Google Search Results

Most Harmful Google Search Suggest With Comma Like Slashdot Article

It appears that the Hard Coded Bias In Google Search Results truely exists as this slashdot article explains last Friday November 19th. We tried to use a comma in the search, however Google continued to supply inaccurate suggestions to the searcher.

The slashdot article continues by explaining "Queries in other categories provide links to not only Google services but also their preferred partners." Google claims it does not bias its results. Edelman cites a 2007 admission from Google's Marissa Mayers that they placed Google Finance at the top of the results page, calling it 'only fair' because they made the search engine.

Google Search Bias Evidence

We ran into this similar article claiming to have found New Evidence for Google Search Bias Relevance. Google appears to favor in-house tech. And Google does this by flooding their search pages with pointers and recommendations and corrections. This will harm businesses.

Funny Google Search Suggestions

Humor is found when Google's Suggestions are off color and slightly entertaining. Here are 25 Funny Google Search Suggestions examples of funny recommendations. Another link to the Funniest Google Suggest Results shows additional samples of humorous search suggestion behavior.

]]>
<![CDATA[It's not Real-time]]> http://itsnotrealtime.com/ It's not Real-time]]> <![CDATA[Neato! I just submitted my first paid app to Palm!]]> http://blog.zhephree.com/post/1018201532/neato-i-just-submitted-my-first-paid-app-to-palm Neato! I just submitted my first paid app to Palm!]]> <![CDATA[Comet Push - alternativa mai buna pentru Ajax]]> http://www.tutorialeonline.net/ro/article/comet-push-alternativa-mai-buna-pentru-ajax Comet Push - alternativa mai buna pentru Ajax]]> <![CDATA[Zhephree Speeks Real-time at HP webOS Developer Day NYC 2010]]> http://www.pubnub.com/blog/zhephree-speeks-real-time-at-hp-webos-developer-day-nyc-2010

Zhephree Speeks Real-time at HP webOS Developer Day NYC 2010

November 18th, 2010 The webOS Developers event in New York will span two days this week on Friday 19th and Saturday 20th. Geoffrey Gauchet CEO of Zhephree will be speaking during the Lightening Round Sessions at 1:00pm this Saturday at the HP/Palm webOS Developer Day Event. The talk will focus on Neato! and Real-time Push Notification options available to webOS Developers.

Neato! and Real-time with PubNub

The focus with the scheduled presentation is primarily how, with webOS's lack of push notifications, Geoffrey Gauchet added this technology in his Company's app called Neato! This nifty and Neato! app is essentially a beefed-up version of Google's Android App called Chrome to Phone.

Using PubNub was a quick and inexpensive way to deploy Real-time Message Delivery into Neato! without having to worry about server capacity or maintenance. Neato! is usable on all major browsers and OS's.

New features expected in the next release of Neato! will be announced during the conference. Neato! cost a very reasonable $1.43 which covers the server costs for push notifications with PubNub and to generate URLs.

HP webOS Developer Day New York

Geoffrey Gauchet's talk will cover the aspects of how Neato! works. Sending and receiving URLs and other data to and from the phone and computer is tricky. The solution really needs to be something which is instantaneous. There is no native push support in webOS and methods like email and SMS will not work in this manner.

Also it is important the solution offer rapid development before the idea was taken. The solution: PubNub which is a third-party hosted PubSubHubub-like service. A full set of APIs allows fast development for Push Notifications on webOS. Simply copy and paste a few lines of code to get started. It's free to get started using PubNub with the 'demo' keys noted half way down on the price page.

Neato! to Your Phone

Neato! uses webOS's default apps to launch special URLs, such as Google Maps URLs. Use Neato! to have a Google Maps link open in Sprint or VZW Navigator and other webOS devices. Neato! works by using your phone's embedded Device ID to calculate your special URL and your custom bookmarklet.

Many new innovations are on the way for Neato! App. Make sure to attend the webOS Developer Day on Saturday to hear Geoffrey Gauchet's talk.

Today Neato! App can push text data into other apps like BadKitty and Pack ‘n’ Track. Neato! will make sure Maps and YouTube videos open in their respective apps when the link is sent from your computer.

Read more about Real-time webOS development with Push Notifications for Games using PubNub.

]]>
<![CDATA[webOS Real-time with PubNub]]> http://www.pubnub.com/blog/webos-real-time-with-pubnub

webOS Real-time with PubNub

November 18th, 2010 Here at PubNub we spoke with active webOS Entrepreneur Jordan Gensler about his success with his comapny's webOS Checkers App which received 400,000 downloads since it launched. Jordan Gensler, CEO of Keen Studios is the man behind this success, powering applications with Real-time interactivity using PubNub APIs. Keen Studios was founded in Portland Oregon, a common place for tech these days.

Jordan has been working with webOS's JavaScript since the first release of the webOS SDK. He has been developing websites from the age of 12 and is knowledgeable in C and C++ coding, as well as PHP, mySQL, SQLite and a few other random yet fun basic-style programing languages that nobody has heard of.

The website of Keen Studios is keen-studios.net, which will finally relaunch after the official Villo announcement.

Keen Studios' Checkers

Checkers has an updated launch menu (seen to the left) where players start out before playing a game. Begin a local game by touching the first menu item and pick a single player match with the computer's AI or decide to play with a friend in two player mode.

The second menu item connects you directly with eager to battle checkers gamers world wide. This will let you play games with your friends as well.

The in-game screen is recognized as a checkered board with shiny red and black player pieces. Each player takes a turn by moving a single piece. Attack your opponent by jumping over her player pieces. Achieve victory after capturing all opponent's player pieces.

The online multiplayer aspect to Keen Studios' Checker App will be released soon. However don't wait for the update, we recommend downloading a copy today to get your strategy nailed down before competition gets hot. Checkers Pro costs the low price of $0.99 so start playing using your webOS Palm device by downloading Checkers App.

Read more about Keen Studios' plans for the future at webOS Developer Keen-Studios talks up Checkers 2 and webOS development and App Spotlight: Checkers Pro & Keen Studios.

webOS with PubNub Messaging

Chat is included with Checkers allowing players to communicate directly while playing in multiplayer mode with friends or anybody else gaming on the cloud. Two multiplayer game modes are available in Checkers 2 Pro: Challenge and Automatch.

With Automatch you will be connected directly with a random player opponent.

Challenge mode allows you to select from a list of players currently online. Read further about the multiplayer plans while Keen Studios connects us to our friends with multiplayer webOS games. Keen Studios' games will take advantage of the latest PubNub 3.0 API for Real-time capabilities. They plan to release each game with multiplayer for all of their webOS games.

HP webOS Developer Day New York

The webOS Developers event in New York will span two days this week on Friday 19th and Saturday 20th. During the Event, Jordan Gensler's fellow developer Geoff Gauchet, zhephree.com, will be speaking about PubNub! Also a member of a partner company to Keen Studios, webOS World, will be attending the event, and showing Real-time technology and Keen Studios Games to interested developers first-hand.

Continue Reading: About PubNub and webOS Developer Day in New York

]]>
<![CDATA[How To Real-time Multi-touch]]> http://www.pubnub.com/blog/how-to-real-time-multi-touch

How To Real-time Multi-touch

September 29, 2010 Learn how to use your fingers to transmit touch events to anyone in real-time. Follow this PubNub tutorial to learn how to use JavaScript Native Touch Events to capture your fingers' position and transmit coordinates in real-time.

Try it out!

Real-time Multi-Touch iPad Room

*** Performance depends on network speed.

GitHub - Source Code - JavaScript

This tutorial is composed of several steps which describe the process of transmitting real-time touch events.

Step 1: Subscribe

First a real-time connection must be open to receive touch coordinates from other people. To open a connection, call the PUBNUB.subscribe() function. The following code is used to listen for touch events from other people:

// Listen for Touch Coordinates
PUBNUB.subscribe({
    channel  : 'touch-receive',
    callback : update_player
});

The code above opens a connection with the channel 'touch-receive' which listens for touch events from other people. This means when another person moves their finger or mouse around the screen, their coordinates will be transmitted to everyone's screen. This of course needs to be programmed. This guide will walk you through how to program real-time coordinates transmission.

Step 2: Touch Events

Next, capture each finger's position on the screen. To do this, a browser's event object is needed. The event object is available when binding events to the document. The following events are of interest in this tutorial:

mouseup, mousedown, mousemove, touchmove, touchstart, touchend and selectstart

PubNub comes with a device agnostic event binding function perfect for binding multiple events to the document. Here is an example of how this is done:

// Set Browser to Gaming Mode
PUBNUB.bind(
    'mouseup,mousedown,mousemove,touchmove,' +
    'touchstart,touchend,selectstart',
    document,
    update_pointer
);

Each event is bound to a master touch tracking function called update_pointer(). This function's purpose will grab the first event fired by the browser containing touch coordinates and prevent remaining events from bubbling. The event object contains touch coordinates. Here is the update_pointer() function which captures touch coordinates:

// Capture Touch Coordinates
function update_pointer(e) {
    var pointers    = current_player.pointers = mouse(e)
    ,   offset_top  = offset( painter, 'Top' )
    ,   offset_left = offset( painter, 'Left' );

    // Apply Touch Offset
    each( pointers, function(pointer) {
        pointer[0] -= offset_left + 20;
        pointer[1] -= offset_top  + 60;
    } );

    // Draw Touches Locally
    update_player({
        pointers : current_player.pointers,
        uuid     : '',
        now      : now()
    });

    // Send Coordinate Information
    publish_updater();
}

The update_pointer() function these does four things:

  1. Capture Touch Events.
  2. Apply Touch Offsets from center of page.
  3. Draw Touches Locally on Browser - update_player()
  4. Send Touch Coordinates - publish_updater()

The function starts by capturing all touch X/Y Coordinates with a function named mouse(). This is a cross device function which detects one mouse cursor or multiple finger touches. It is a simple function which returns an array of [ x, y ] coordinate pairs:

function mouse(e) {
    // Bubble if No Touch Coordinates
    if (!e) return [[0,0]];

    // Detect Touch Coordinates Available
    var tch  = e.touches && e.touches[0]
    ,   mpos = [];

    // Touch Coordinates
    if (tch) {
        PUBNUB.each( e.touches, function(touch) {
            mpos.push([ touch.pageX, touch.pageY ]);
        } );
    }
    // Mouse Coordinates
    else if (e.pageX) {
        mpos.push([ e.pageX, e.pageY ]);
    }
    // Mouse Coordinates IE
    else { try {
        mpos.push([
            e.clientX + body.scrollLeft + doc.scrollLeft,
            e.clientY + body.scrollTop  + doc.scrollTop
        ]);
    } catch(e){} }

    // Return Captured Coordinates
    return mpos;
}

The mouse() function captures both standard mouse coordinates and finger touch coordinates. If using an iPhone/iPad/Android device, the mouse function will return an array of arrays which looks like this (with three (3) fingers):

[ [x,y], [x,y], [x,y] ]

Step 3: Publish

Next, send the captured coordinates. This is done by executing the PUBNUB.publish() function. Before this is done however, identification of the device sending the coordinates is important. Knowing which device the touch event comes from allows for tracking movement of each unique finger. Each device is tracked by a UUID generated from the PUBNUB.uuid() function.

// Create UUID
PUBNUB.uuid(function(uuid) {
    console.log(uuid);
});

Beware, there is another pitfall! Those readers who have bound mouse movement events before know that between 100 and 900 events fire each second. If the PUBNUB.publish() function is called to frequently, network slamming will occur. When this happens, players will quickly saturate their bandwidth. It is best to transmit only a few coordinate pairs per second. Therefore a special purpose updater factory is necessary. The following function limits the rate of updates to prevent network slamming while always sending the latest information.

// Provide Rate Limited Function Call
function updater( fun, rate ) {
    var timeout, last = 0;

    // Return Rate Limited Function
    return function() {
        var right_now = now();

        // Time to Execute Function?
        if (last + rate > right_now) {
            clearTimeout(timeout);
            timeout = setTimeout( runnit, rate );
        }
        else {
            last = now();
            fun();
        }
    }
}

The updater() function provides a simple interface for creating a rate limited function. It's a function which returns a function. When a rate limited function is called, even if it is called 100,000 times in a second, the inner function will only be called as often as specified. Here is how to use the updater() function:

// Called on Touch Move Events
var publish_updater = updater( function() {
    // Must be Ready Before Sending.
    if (!current_player.ready) return;

    // Send Player Touch Coordinates.
    PUBNUB.publish({
        channel : 'touch-receive',
        message : {
            pointers : current_player.pointers,
            uuid     : current_player.info.uuid,
            last     : last++
        }
    });
}, wait );

The inner function uses PUBNUB.publish() to transmit touch coordinates on the 'touch-receive' channel. Note that the message contains three variables.

  1. pointers - touch coordinates array.
  2. uuid - device UUID.
  3. last - last transmission counter.

This data is transmitted to anyone listening on the 'touch-receive' channel. With this information, all fingers and mice can be drawn on everyone's screen at the same time with live positioning. The last transmission counter is used to identify which message is the most recent. PubNub's Cloud Service does not guarantee ordered message delivery. It is important to send message-counting-information when chronology is needed.

Step 4: Draw

The final step is to draw the received coordinates. This is done by adding an absolutely positioned div to the document. The div will of course have a nifty background image. In the case of this tutorial, the background image will be a fingerprint. The draw function is called update_player(). Here is the source of update_player():

// Called for All Touch Events (from everyone)
function update_player(message) {
    var uuid     = message['uuid'] || 'self'
    ,   last     = message['last']
    ,   pointers = message['pointers']
    ,   i        = 0;

    // Leave if transmitted coords from yourself.
    if (!current_player['info']) return
    if (uuid == current_player.info.uuid) return;

    
    // Is this a New Touch?
    if (!points[uuid]) {
        points[uuid] = {
            last    : last,
            touches : []
        };
    }

    // For Each Pointer
    each( pointers, function(point) {
        // Create Sprite DIV for the Pointer
        if (!points[uuid].touches[i]) {
            points[uuid].touches[i] = {
                xy     : point,
                sprite : sprite.create({
                    image : {
                        url    : 'print.png',
                        width  : 40,
                        height : 60,
                        offset : {
                            top  : 0,
                            left : 0
                        }
                    },
                    cell : {
                        count : 1
                    },
                    left : point[0],
                    top  : point[1],
                    framerate : 60
                })
            };

            
            // Set Random Fingerprint Opacity
            var opacity = Math.random();
            css( points[uuid].touches[i].sprite.node, {
                opacity :
                    opacity < 0.5 ?
                    0.5           :
                    opacity
            } );
        }

        
        // Draw Self Touches
        if (uuid == 'self') {
            css( points[uuid].touches[i].sprite.node, {
                left : point[0],
                top  : point[1]
            } );
        }
        
        // Draw Remote Touches (From other People)
        else {
            sprite.move( points[uuid].touches[i].sprite, {
                left : point[0],
                top  : point[1]
            }, wait );
        }

        // Next Pointer
        i++;
    } );
}

This function gets called when a message is received in Step 1: PUBNUB.subscribe(). As you can see, a lot happens in the update_player() function. Its main purpose is to draw pointers on the screen. There is no upfront limit to the number of pointers/touches drawn. Notice the references to the sprite object. This object provides animation tweening between points transmitted from the PUBNUB.publish() function. This provides a smooth look with moving fingers and updated coordinates.

GitHub - Source Code - JavaScript

Visit the GitHub link to see all the code put in one piece.

Step 5: Bonus Tuning

Several highly useful tactics will provide a smooth user experience. The following tips will provide helpful as guidelines in all real-time applications built on any platform or service.

Prevent Event Bubbling

The PUBNUB.bind() function provides by default event bubbling prevention. This awards the opportunity to enable a gaming type mode in the web browser. This will prevent page scrolling and stop context menus from interrupting gameplay.

    e.cancelBubble = true;
    e.returnValue  = false;
    e.preventDefault();
    e.stopPropagation();

The PUBNUB.bind() function does cancels event bubbling by default. This also speeds up the browser in some cases.

Draw Local UI Changes First

A great tactic to provide fast UI and improved user experience is to draw all local changes before sending updates remotely. This will dramatically improve perceived performance. Drawing local User changes will provide smooth and non-jumpy graphics.

Always Out of Date

This is important! Always assume everyone is out of date. With real-time applications, this is critical. Especially since network connections drop unexpectedly for many reasons. Also a person may refresh the page (F5) or leave by accident. Therefore, always send and receive data whenever something has changed. Keeping the mindset of "everyone is always out of date" allows more stable application development practices. Finally provide an interface which allows piers to asking each other the question: "Am I up to date?".

Sessions with UUID

Utilize the PUBNUB.uuid() function. This offers a way to identify each device and browser uniquely:

// Create UUID
PUBNUB.uuid(function(uuid) {
    console.log(uuid);
});

The UUID can be used as a one-time session token. This can be passed in the publish() message to identify the origin of messages from unique sessions. Optionally store the UUID in a cookie or localStorage to provide longer lasting sessions.

Time Synchronization

Utilize the PUBNUB.time() function. This provides a timestamp which can be used to synchronize players who are in different time zones or who have suspect local clock accuracy.

// Get Current Timestamp
PUBNUB.time(function(time) {
    console.log(time);
});

Never trust the player's local clock. Use the PUBNUB.time() function to synchronize players.

Animation Tweening

Make sure to use a keyframe framework which can animate between two points. PubNub provides a Sprite Keyframe Tweening Framework. It is remarkably lightweight and provides PNG animation support for cell based animation. There is no documentation for sprites, however this tutorial uses the sprite animation functions and it is easy to see how the functions can be used by example.

CSS Helpers

The following is a collection of CSS attributes which improve user experience for games in the browser especially in webkit and mobile phones. The following CSS is in use for this tutorial:

    body {
        margin: 0;
        padding: 0;
        height: 100%;
        overflow: hidden;
        overflow-y: hidden;
        -webkit-user-select: none;
        -webkit-touch-callout: none;
        -webkit-tap-highlight-color: rgba(0,0,0,0);
        -webkit-text-size-adjust: none;
    }

These CSS attributes assigned to the body selector prevent page scroll bars. The webkit CSS attributes prevent text from being selected in Android iPhone, iPad, iPod, Safari and Chrome.

Mobile Meta Tags

Include Mobile Meta Tags in the header section of the HTML file. This offers a resolution guideline for mobile browser to follow:

  1. Game Width/Height - <meta name=viewport content='width=320, height=480, user-scalable=0' />
  2. Load Bookmarked Page Without Mobile Safari - <meta name=apple-mobile-web-app-capable content=yes>
  3. Hide Status Header - <meta name=apple-mobile-web-app-status-bar-style content=black-translucent>
    <meta
        name=viewport
        content='width=320,height=480,user-scalable=0'>
    <meta
        name=apple-mobile-web-app-capable
        content=yes>
    <meta
        name=apple-mobile-web-app-status-bar-style
        content=black-translucent>

PubNub Real-time

Take advantage of the PubNub Real-time Cloud Service. There are only two functions you need to know: PUBNUB.publish() and PUBNUB.subscribe(). Our JavaScript Push API focuses on speed and usability.

Get the PUBNUB JS Include

]]>
<![CDATA[Real-time Multi-touch]]> http://www.pubnub.com/blog/real-time-multi-touch

Real-time Multi-touch

September 24, 2010 Use your fingers to transmit touch events to anyone. PubNub uses JavaScript Native Browser Touch events to capture your fingers' position and transmit them in real-time. Try it out!

Real-time Multi-Touch Room

*** Performance depends on network speed.

Source Code - JavaScript

Finger Attack!

We have a few iPads and iPhones to play with at PubNub. We used our hands to move around each other's fingers in real-time. "Don't touch my fingers!" and "I attack you with my finger!" are a few phrases used during our tests.

Usage of Multi-touch and Real-time

PubNub is changing the "closed web" into the "real-time web". Right now the web is ready to be augmented with real-time. Amazing things will be built. A Real-time Craig's List. What would that look like? We are not sure, though we know it will be built someday. A Real-time E-commerce will be built too. Who will build it first? Some one will and it may be you.

E-commerce today is like a grocery store at 3:00am, no one is around and the isles are empty. However, time-of-day on the internet doesn't matter. There is always someone online. Someone is standing in the same tea + coffee isle your in right now. But you can't see them, yet.

Multi-Device Compatible

PubNub can live on any device. The device will have web rich capabilities and be connected to the internet. Such as iPhone, iPad, Android, Blackberry, Windows Phone, Symbian and the ordinary laptop and desktop computer.

Meaning of Real-time

Humans leave their ears open for incoming sound. When another human shouts, everyone hears the information instantly. Today the internet is like a human with shutter closed hearing. When a human shouts on the internet, no one hears this.

Communication is slammed against the internet's shutter door and the information is squashed up. When a human visits a website or presses F5 (refresh), the shutter doors are opened with a downpour of information. PubNub removes the shutter doors on the internet. With PubNub you can build apps that stay open and clear. Information is allowed to flow. Today at PubNub, we have removed the shutter doors for multi-touch. There are more doors and shutters to break down. We are excited to see which one will be next.

]]>
<![CDATA[Real-time Data Delivery: HTTP Streaming Versus PubSubHubbub]]> http://blog.programmableweb.com/2011/01/06/real-time-data-delivery-http-streaming-versus-pubsubhubbub/ Real-time Data Delivery: HTTP Streaming Versus PubSubHubbub]]> <![CDATA[PubNub Channel API Monitor]]> http://donaldknuth.blogspot.com/2010/12/channel-apimonitor.html PubNub Channel API Monitor]]> <![CDATA[Facebook "Meh" Button]]> http://www.pubnub.com/blog/facebook-meh-button

Facebook "Meh" Button

August 9th, 2010 Yesterday, BoingBoing posted an article with a new Facebook Icon for "Meh" Button, opposed to "Like". Inspired by this, PubNub developers built the Facebook "Meh" Button and added real-time to it. This button can be used with the Facebook "Like" button or standalone.

The Facebook "Meh" Button, opposed to "Like".

Get the Facebook "Meh" Button

Add Facebook "Meh" Button

Click the big blue button above to get the Facebook "Meh" Button for your website. It is a simple copy/paste.

Real-time "Meh"

Facebook "Meh" Button is Real-time. When clicked, the number goes up on everyone's computer screen, instantly. Why build real-time apathy? It's important to see exactly how many people don't care without needing a page reload. Here at PubNub, this is vital.

Open Source on GitHub

This code is 100% open for the public. Visit the code repository Facebook Meh Button from PubNub on GitHub. The code is written using PubNub's API. Graphics were created in Gimp on Linux.

Create Real-time Apps with PubNub

How did we create this button of "Meh"? We used PubNub's API. PubNub Real-time works on all devices, including mobile phones. Go to the Tutorial for Developers to learn how to use the API.

Inspiration of "Meh"

The Facebook "Meh" Button was inspired by the article posted on BoingBoing: Proposed Facebook icon for "meh" as opposed to "like". The article talks about the opposite of the Facebook "Like" Button. An image was drafted by obeyken "Ken Murphy" titled "Meh". Because of this, PubNub built the Facebook "Meh" Button while listening to Donkey Kong Country Music from the SNES version.

Facebook "Meh" Icon Suggestions

If you have a suggestion or want to supply a different "Meh" Icon, then contact us with a link pointing to the icon. We'll update this blog with your suggestion and may change the icon that is distributed with the widget. We look forward to some ideas.

Optional Single Click Limit

    <div id="facebook-meh-button" one-click-per-person="on"></div>

To cap the number of clicks per perons, set the attribute one-click-per-person="on" in the DIV. This prevents a single person from showing more than her fair share of not caring.

No Association with FB

This button is not associated with Facebook. This button was created by PubNub Developers. Click here to contact us.

]]>
<![CDATA[NY Daily News: When you care enough to click: Proposed "Meh" Facebook button]]> http://www.nydailynews.com/lifestyle/2010/08/13/2010-08-13_what_do_you_think_of_my_facebook_post_meh.html NY Daily News: When you care enough to click: Proposed "Meh" Facebook button]]> <![CDATA[UPI Odd News - "Meh" button spreads across Internet]]> http://www.upi.com/Odd_News/2010/08/16/Meh-button-spreads-across-Internet/UPI-39701281992144/ UPI Odd News - "Meh" button spreads across Internet]]> <![CDATA[The Hindu: Too bored to comment? Click "Meh" button on Facebook]]> http://www.thehindu.com/sci-tech/internet/article570845.ece The Hindu: Too bored to comment? Click "Meh" button on Facebook]]> <![CDATA[The Daily Beast: Developer Proposes "Meh" Facebook Button]]> http://www.thedailybeast.com/cheat-sheet/item/developer-proposes-lsquomehrsquo-facebook-button/who-cares/ The Daily Beast: Developer Proposes "Meh" Facebook Button]]> <![CDATA[TopNews: Too bored to comment? Click "Meh" button on Facebook]]> http://www.topnews.in/usa/too-bored-comment-click-meh-button-facebook-25153 TopNews: Too bored to comment? Click "Meh" button on Facebook]]> <![CDATA[Long Live Apathy! Introducing the Facebook "meh" Button]]> http://thenextweb.com/socialmedia/2010/08/09/long-live-apathy-introducing-the-facebook-meh-button/ Long Live Apathy! Introducing the Facebook "meh" Button]]> <![CDATA[Jeg gir «MEH» i dette!]]> http://www.itavisen.no/848588/jeg-gir-%ABmeh%BB-i-dette Jeg gir «MEH» i dette!]]> <![CDATA[Forget the Facebook Dislike button. Here is the Meh button]]> http://www.instantfundas.com/2010/08/forget-facebook-dislike-button-here-is.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed:+InstantFundas+(Instant+Fundas) Forget the Facebook Dislike button. Here is the Meh button]]> <![CDATA[PHP Push API Walkthrough]]> http://www.pubnub.com/blog/php-push-api-walkthrough

PHP Push API Walkthrough

July 20th, 2010 PubNub adds Publish and Subscribe for PHP developers. Developers can use Publish/Subscribe from a terminal or web server like Apache/NginX/lighttpd. PubNub PHP Push API provides real time Publish and Subscribe for PHP Developers.

This means JavaScript Browsers can push messages to PHP servers. JavaScript Browsers can also push to PHP command line programs running in a terminal. All APIs are 100% Real Time.

This Walkthrough is meant to work on your laptop in a terminal/console! If you don't have a terminal/console, then read the JavaScript Push API.

Ruby, JavaScript and C# Push APIs are available on GitHub. Download PubNub API on GitHub

PHP developers can push messages to JavaScript Browsers. Read PHP Push API Reference Tutorial for a condensed reference of API function calls.

JavaScript PHP Push API "Hello World"

Let's take a look at how developers can create channels between PHP and JavaScript. The most common usage pattern for real time applications will be explained first. A JavaScript Browser (like Firefox) will subscribe and listen for messages with PUBNUB.subscribe(). PHP will then push messages with $pubnub.publish().

JavaScript

PUBNUB.subscribe( { channel : 'my_test_channel' }, function(message) { if ('some_text' in message) { alert(message.some_text); } } );

The above JavaScript is 100% Cross Browser Compatible. The code will listen for messages published on 'my_test_channel' channel. When a message is received, the JavaScript will validate if 'some_text' exists in the message object. If this attribute exists, then show an alert box!

Now use PHP to publish a message to invoke the JavaScript Alert box.

PHP

## Publish Messages To a JavaScript Browser $pubnub = new Pubnub( 'publish_key', 'subscribe_key' ); $pubnub->publish(array( 'channel' => 'my_test_channel', 'message' => array( 'some_text' => 'hello!' ) ));

This PHP code will send a message to a JavaScript Browser listening on 'my_test_channel' channel. When this PHP Code executes, a JavaScript Browser will receive the PHP array and show an alert message of 'hello!'.

Send Messages to PHP from JavaScript

This next example is uncommon, albeit powerful. JavaScript has the capability to send messages to PHP. PUBNUB.publish() in a JavaScript Browser will send real time messages to a PHP Script.

This PHP Script will be listening with $pubnub.subscribe(). PHP can receive messages directly from a JavaScript Browser. Here is the PHP Code:

PHP Listens for a Message

$pubnub->subscribe(array( 'channel' => 'extra_cool_channel', 'callback' => function($message) { var_dump($message); return true; ## continue listening } ));

The above code makes PHP listen on 'extra_cool_channel' channel. Next we send messages from JavaScript to PHP. Note that this PHP code may be running in a terminal window.

JavaScript

PUBNUB.publish({ channel : 'extra_cool_channel', message : { 'some_var' : 'what up?' } });

When we execute this JavaScript code, the PHP Script will receive { 'some_var' : 'what up?' } message. The output of the PHP Script will look like:

PHP Output

array(1) { ["some_var"]=> string(8) "what up?" }

That's it. Pretty simple right? This code works without needing a web server! It will work on your laptop right now!

You need Publish and Subscribe Keys. Publish and Subscribe Keys are needed for every PubNub application. Grab API Keys with the link below. Get API Keys

PHP Command Line Chat Video

The video demonstrates a CLI (Command Line Interface) PHP Chat Client. It uses real time PubNub Publish and Subscribe Framework for PHP Developers.

PHP Chat Program Using Open Source Pubnub API

The link below will take you to the PHP Push API Reference Page with a full list of available API calls. PHP Push API Reference Tutorial

]]>
<![CDATA[CSS3 Performance Optimizations]]> http://www.pubnub.com/blog/css3-performance-optimizations

CSS3 Performance Optimizations

July 2nd, 2010 Today with CSS3 selectors, more advanced and wonderful pathways to DOM components are available. Fancy new visuals are possible as well. These visuals and selector additions, like with CSS2, can be overused to a point of poor user experience. Is the snappiness of the web gone forever?

Fastest CSS3 Selectors

Selectors as classes and subclasses with child selections based on DOM Element types can make your CSS development life easy. Capturing elements with attributes set to specific values or substrings will create exciting dynamic flow.

Don't do it! The browser will slow down. The complexity for parsing display over the document is significant. CSS3 syntax improvements are not free; chunks of CPU is the price. Use the fastest selectors. These selectors work on all browsers. These two selectors are the most simple and basic. The number one fastest selector in the world today is #id {}

Good:

    #id-selector {}
    .class-selector {}
    custom {}

Bad:

    a {}
    div {}
    span {}
    .class .class {}
    a.class {}
    li.class {}
    div.class {}
    div[attr=something] {}
    div > a.class {}
    span div.class {}
    span div {}

To make your site fast. Use light weight selectors. This makes your site fast for old and new devices and browsers.

Why Some CSS3 Selectors are Faster

The reason behind performance boosts by excluding advanced CSS3 selectors is related to how the document applies style computations to document elements. The following is a slow and heavy selector:

    div#nav a {}

The browser will first select all <a> tags in your document. Then it will iterate a second time over the list of the anchor tags in search for any anchors inside the #navigation id element. This is slow. Instead use this:

    .nav {}

Apply the .nav class to every anchor tag individually.

HTML5 Document Syntax

Might as well take advantage of HTML5/4 document syntax when using CSS3. Start by reducing page size by excluding syntax:

Good:

    <div id=my-id class=fish></div>

Bad:

    <div id="my_id" class="fish"></div>

Save bytes by excluding syntax making a faster download.

Use the HTML5 doctype. The doctype is small and light weight.

Good:

    <!doctype html>

Bad:

    <!DOCTYPE html PUBLIC
        "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

Use <custom>Tags</custom>.

    <pub>PubNub<pub>

And the CSS3 Selector will be:

    pub {color:#f90}

Use CSS3 Shorthand

When possible, use the shorthand notations for defining styles.

Good:

    background:#fff;
    color:#000;
    padding:2px 3px 4px 5px;
    margin:10px;

Bad:

    background-color: #ffffff;
    color: #000000;
    padding-top: 2px;
    padding-left: 3px;
    padding-bottom: 4px;
    padding-right: 5px;

Reducing payload size by using CSS3 shorthand to increase payload delivery.

Avoid Inline Styles

The following will slow down your page considerably:

Bad:

    <div style='color:yellow;'></div>

Avoid this or suffer extra CPU cycles on the end user's machine.

One CSS3 Stylesheet Per Page

If you have multiple style files, merge them into one. If required to have multiple style files, place these extra styles directly on inside the HTML Document Head.

Reduce Payload Size of CSS3

Both Gzipping and Minifying your CSS3 is important for speedy delivery. Running your CSS3 into a minifier will reduce size by 30%. Gzipping will reduce by 40%. Here is a Perl Script we use to Minify our CSS3:

Good:

    #!/usr/bin/perl
    my $build = q();
    while(<>) { $build .= $_; }
    $build =~ s/\/\*.*?\*\///msg;
    $build =~ s/\s+/ /msg;
    $build =~ s/ ?([;:{}]) ?/$1/msg;
    $build =~ s/;+\}/}/msg;
    print $build;

Use this script on your CSS3 Files like this:

Good:

    ./minify styles.css | gzip -c9 > style.min.css

Now you have the best payload package for your CSS3.

Advanced CSS3 Optimizations

Distribution and deployment strategies will be the final speed boost optimizations. Make sure your CSS3 payload HTTP Headers are set as follows:

Good:

    Content-Type: text/css
    Content-Encoding: gzip
    Content-Length: 4543
    Expires: Thur, 01 Jan 2020 10:00:00 GMT
    Cache-Control: public
    Connection: close
  • Content-Type tells the browser what is being downloaded.
  • Content-Encoding meas it is compressed.
  • Content-Length tells the browser when to execute the moment it receives the last byte without waiting for the connection to be closed.
  • Expires prevents HEAD request revalidation.
  • Cache-Control allows nearby proxy caching.
  • Connection close instantly after all bytes read.

Exclude all other headers, especially the ETag header.

CSS3 Content Delivery Network (CDN)

Place your final package on a CDN. Google App Engine, Amazon Cloud Front and Rackspace Cloud Files are options we have used and recommend for entry level performance and pricing. This is one of the fastest delivery boosts in performance. Using a CDN will increase page responsiveness 2-8x boosts. Even if you choose to skip other optimizations, this one is an easy mega boost.

PubNub and CSS3 Optimizations

Here at PubNub we use these strategies, mostly. We are in an attempt to make the web a faster place! These same optimizations apply to JavaScript as well! Read about JavaScript Optimizations in the following link. Fastest Javascript Google Closure Gzip -9 Memcache CDN

]]>
<![CDATA[Scaling in the Clouds]]> http://www.pubnub.com/blog/scaling-in-the-clouds

Scaling in the Clouds

June 30th, 2010 PubNub and Techzing talk for an hour about PubNub architectures, alternatives, performance and scalability in the cloud. Our conversation hits business startup challenges and today's exciting real time tricks.

Listen to the co-founders of PubNub
Interviewed on Teczhing

Scaling in the Clouds

The term Cloud is buzzy. For many people it is an auto-scaling server framework. To others it means hoards of on-demand virtualized OS hives. These two definitions can be true at the same time. Both are true for PubNub.

We've taken the route of auto cloud scaling for our message bus. Based on the number of current standing connections we grow or shrink our running server count. There are two thresholds that we've marked at 20% and 80%. The 20% resources mark means there are more servers running than needed. We will spin down servers until the resource level reaches close to 50%. 80% usage invokes the opposite by launching extra servers. And of course each server knows to launch our messaging bus daemon automatically on boot.

This scaling approach makes the most sense for PubNub. But what about the standing connections which may still be attached to a system that gets shut down? These will auto re-route to a running box by re-requesting a connection port from an origin server which monitors analytics and system health.

There is no special magic with cloud scaling. Cloud scaling is specific to your architecture. Focus on simplicity and efficiency. Do not build fancy slow frameworks. And Make sure to split components logically into separate services. Abstract all business rules from your cloud service somewhere else. Simplicity is most important.

Techzing Interviews PubNub

Hosts of Techzing Jason and Justin interviewed the co-founders of PubNub. Discussions rounded several conversation topics including cloud scaling, business spanning and options for real time solutions.

PubNub started as an auto scaling horizontal messaging bus. Now we provide demonstrations of vertical solutions. Open Source examples of vertical business pathways include: Mouse Speak as interactive collaboration, Traffic Beat shows analytics, and Simple Chat will explain the basics.

Our next vertical target will be gaming. We'll launch a simple yet fun real time action game. Building real time applications is easy because the PubNub real time platform is complete.

Scaling in the cloud isn't 100% on the tech dev side, it involves biz dev too. Decisions must be made in directions of growth potential. Business and Technical development lean on one another.

Cloud Services used by PubNub

Here at PubNub we use a combination of three cloud services. Google App Engine, Amazon Web Services EC2 and RackSpace Cloud. We take advantage of the strengths for each of these services. App Engine is used for simple analytics and tracking of customers. AWS EC2 and RackSpace Cloud are used together for redundancy as core connections running our message bus.

App Engine tracks customer API Keys. It is also the face the primary PubNub website. We host applications in the Application Showcase on App Engine and distribute the PubNub JavaScript Push API payload.

We use Rackspace and Amazon for our long standing connections provided by our proprietary messaging bus service. Each virtual cloud box runs our custom distributed socket pusher.

Stable Cloud Services

PubNub has a complete cloud architecture. We launched three weeks ago and continue to grow faster than expected. What is our Success Juice?: Solve the technical hardships in scaling with simplicity, provide an API focused on simplicity and rendered a fine strawberry jam for application bagels.

How can we help you with Real-Time? ]]>
<![CDATA[Mouse Speak]]> http://www.pubnub.com/blog/mouse-speak

Mouse Speak

June 28th, 2010 We Mouse Speak, mousing with fellow web people. As you can see, Mouse Speak is an interactive real time connection between multiple humans and their mice. Mouse Speak launched last week here at PubNub.

Watch PubNub Mouse Speak

What is Mouse Speak?

A shadow mouse tracks your movement. As your shadow mouse moves, it moves on other peoples screens; at the same time. Type on your keyboard, everyone sees your keystrokes. Click and leave mouse tracks.

Adding Mouse Speak on Your Website

Mouse Speak can be installed on your website instantly by copy and paste. It is a simple JS include combo with zero configuration required!

Add Mouse Speak on My Website

Mouse Speak Video

Everyone left the mouse floor? Watch the video to see what it can be like when your friends join PubNub Mouse Speak . This 30 second video demos the connection between humans and their mice.

Techzing and Mouse Speak Project

Check out Jason and Justin on Techzing as they have a conversation about real time comet and the latest on the edge technologic. PubNub gives thanks for the contributions from Techzing's Hosts Justin Vincent and Jason Roberts.

Techzing
News and views from the front-line of tech & startups

Mouse Speak uses PubNub BOSH

Mouse Speak is 100% JavaScript. It functions by a simple transport concept technology called Comet, also known as BOSH: XEP-0124: Bidirectional-streams Over Synchronous HTTP. PubNub offers this data transport in the form of a messaging bus service in the cloud. So you don't need to worry about the details, PubNub takes care of them for you. This technology is simple enough to work great on all web rich mobile devices. Even iPhone, iPad, Android, Blackberry and Symbian too!

Mouse Speak Source Code on GitHub

Curios about the source code? Every project here at PubNub is open source. If you are a developer, then check out the source code at PubNub API Mouse Speak Source on GitHub . Use the code at GitHub to build on top of our Messaging Service in the Cloud.

PubNub API Mouse Speak Source on GitHub

Does Mouse Speak Cost Money?

Mouse Speak is free up to a limit each day. Learn more about our free quota and pricing details.

]]>
<![CDATA[Techzing Live Mention]]> http://www.pubnub.com/blog/techzing-live-mention

Techzing Live Mention

June 23th, 2010 Everyone at PubNub is totally stoked that Techzing mentioned us on air June 21st, 2010. These guys are fun and informative. This inspired us to be amazing.

Techzing
News and views from the front-line of tech & startups

Techzing Talks Technology

PubNub was mentioned during a Comet technology conversation two days ago on Techzing podcast. Justin and Jason describe the efficiency in using Comet technology and how adding a push server deployment along with your existing web stack is very hard. The tricky part is cross browser implementations and cross domain restrictions with bonus challenges for mobile.

Integrating Comet Push technology with your current web stack is hard because cross domain request become an issue if you are without a running load balancer proxy. Additional concerns are uncovered when you are ready to scale with thousands of standing connections. At PubNub we have taken care of this for you. Check out the podcast on Techzing's website in the following link:

Listen to PubNub and Comet at 30:30 minute

Exclusive Beta

Our next App in the App Showcase will demonstrate the performance capacity of PubNub. We will be working with the Techzing Team to make this app more interesting. We are working together on features and presentation. This effort will shape the next app release for our PubNub App Showcase.

Who is Techzing?

Justin Vincent and Jason Roberts are the hosts of a tech talk show named Techzing. Jason and Justin had their first conversation on Friday the 15th of May in 2009 realizing they live just down the street from each other. Now they host a great talk show via podcast with content about tech startups and trending tech in the news.

PubNub has been invited as a guests to join Justin and Jason in a discussion about comet technology and to dispel mysteries around real time push frameworks. We are looking forward to this conversation!

Techzing Podcast ]]>
<![CDATA[Ruby Push API]]> http://www.pubnub.com/blog/ruby-push-api

Ruby Push API

June 22th, 2010 New Ruby Push API Publish() + Subscribe() Real Time Notifications Framework uses standard Ruby batteries plus JSON. Slots in with Rails and Ruby Applications. Download Ruby Push API on GitHub.

This website is dedicated to Publish() + Subscribe() Realtime Notifications Framework. The concept of Publish + Subscribe is simple. Subscribers are people with phones and browsers. Subscribers receive updates instantly when a message is Published.

Computers can be subscribers too, like a web server or your laptop. This is where the Ruby Push API is helpful.

Download the Pubnub.rb Ruby Push API Client Library on GitHub to follow along if desired.

In the same directory are fun Ruby Push API Examples to play with.

Publish() with Ruby Push API

To send a message to all subscribers, call the publish() function. This function needs a channel and a message. The message is automatically converted to JSON, though you don't need to worry about that because the transport encodes and decodes JSON when necessary. The following code snippet shows how to publish a message.

## Create PubNub Instance
pubnub = Pubnub.new( 'publish_key', 'subscribe_key' )

## Publish (Send Message)
pubnub.publish({
    'channel' => 'my_channel',
    'message' => { 'my_var' => 'my text data' }
})

The above function sends a JSON message to all subscribers. The structure of the message is maintained along the way; no need to worry about encoding or decoding:

{ 'my_var' : ... }

The message structure is portable across all environments (Ruby, JavaScript, PHP, etc.)

You will need to have your API keys from PubNub. Grab your API Keys with the link below. Get API Keys You only need the Publish and Subscribe keys for now. Ignore the Secret Key.

Subscribe with Ruby Push API

To listen for published messages, call the subscribe function. It is important to note: the subscribe function is blocking. You will want to run this function in a separate process. The following code snippet will show how to listen for published messages.

## Subscribe (Listen for Messages)
pubnub.subscribe({
    'channel ' => 'my_channel',
    'callback' => lambda do |message|
        ## Message Received!!!
        puts(message['my_var']) ## print message
        return true             ## keep listening?
    end
})

Once you call this function, it turns your Ruby Script into a mini server which listens for publish events. This function is more involved than publish(), yet remains simple. You must specify a channel and specify a callback function to execute when a message is received. The callback can be a lambda or proc depending on your scope needs. This function will stay connected, forever listening for published messages. This works even behind a firewall! For full reference of functions, visit the following link. Ruby Push API Tutorial Next let's see what we can do inside the Subscribe Callback.

What to do Inside a Subscribe Callback

Your Callback is executed once for each message received. Note there is no enforced schema/format for messges. The structure is up to you and can be any JSON Serializable Ruby Object.

So what do you do with the message? When the callback executes, you may decide to save the message to a database for persistence. Also you may publish this message to other channels by calling pubnub.publish() inside your subscribe callback. These other channels, you can decide, may have JavaScript subscribers on browsers. Totally up to you. Here is a fun dual Ruby and JavaScript example:

Ruby

## Ruby Subscribe (Listen for Messages) pubnub.subscribe({ 'channel ' => 'my_hidden_channel', 'callback' => lambda do |message| ## Message Received!!! ## maybe save to database? save_to_database(message['text']) ## do logic which validates message if message['text'] ## Relay Message to Browsers publish.publish({ 'channel' => 'my_javascript_channel', 'message' => message }) end end })

JavaScript

// JavaScript Subscribe (Listen for Messages) PUBNUB.subscribe({ channel : 'my_javascript_channel' }, function(message) { // Show Message alert(message['text']); } );

The above two boxes show communication between a Ruby script on a server, and a JavaScript in a web browser. The Ruby Script listens for messages published on a hidden channel. If the message is validated it will re-publish the message to browser subscribers for instantaneous updates. More details on the JavaScript Push API can be read in the following tutorial link. JavaScript Push API Tutorial There are many recipes with server and client push APIs. Note that the Ruby and JavaScirpt Push APIs are independent and can be used separately. For example you may Publish and Subscribe directly in a web browser without a server! This works on mobile as well (such as iPhone/Android). If you are interested in a fully functional JavaScript Push API which requires no back-end server, read the JavaScript Push API Tutorial

History API Call

To peak at previously published messages on a specific channel you'll use the pubnub.history() function. This function allows you to recall up to 100 previously published messages within the past few days. The messages expire. Make sure not to depend on this API for persetent storage.

## Load Previously Published Messages
messages = pubnub.history({
    'channel' => 'hello_world',
    'limit'   => 100
})

To improve network performance, especially on mobile JavaScript, request fewer messages with by lowering the limit. Visit the link below for a simple reference of the history() function. Ruby Push API Tutorial Ruby Push API Examples on GitHub

]]>
<![CDATA[JavaScript Push API 2.0 Upgraded]]> http://www.pubnub.com/blog/javascript-push-api-2.0-upgraded

JavaScript Push API 2.0 Upgraded

June 17th, 2010 The new JavaScript Push API 2.0 is faster, simplified and totally answers top requested feature updates including the most requested unsubscribe function.

Download JavaScript Push API
NOTICE: this blog is outdated. There is a newer version of the PubNub Real-time Cloud API. Note however that the API calls mentioned here STILL WORK.

Read: JavaScript Push API For the latest information.

New UnSubscribe() Function Push API

The Top Requested Feature UnSubscribe() is now available. We implemented this function in the new JavaScript Push API 2.0 version. Many requests asking for a way to free subscription resources were sent. Now you can cleanup subscriptions by calling:

// PUBNUB.unsubscribe(args)
PUBNUB.unsubscribe({ channel : 'name_of_channel" });

Read Updated API 2.0 Doc: JavaScript Push API 2.0 Updates

Simplified JavaScript Subscribe API

Other popular requests were for API simplifications. You are no longer required to iterate over messages from the PUBNUB.subscribe() function. See the following code sample.

// PUBNUB.subscribe( args, callback )
PUBNUB.subscribe({
    channel : 'my_channel'
}, function(message) {
    // Show Message
    console.log(message);
} );

The simplification is helpful by reducing client code size. Easier adoption of the API and fewer docs to consider. We've also simplified the History API: History API Tutorial - JavaScript Push API 2.0

Performance Increase of JavaScript Push API 2.0

The 2.0 API provides a faster connection interface to our server clusters in different locales. This means faster communication internationally.

Another boost on our servers updated through memcaching data points allows faster lookup and delivery for all PUBNUB.publish() calls.

Scalability and Redundancy of JavaScript Push API 2.0

The PubNub Server Cluster is still as scalable and redundant as ever before. Pubnub will scale to facebook load and beyond. Over 100 million standing connections without delays. Today our load is more than five hundred thousand standing connections.

PHP Push API 2.0

We've also updated our PHP Push API Client Library. You can find this on GitHub: PHP Push Client Library API 2.0 Updates

jQuery Push API 2.0 Plugin

We've released the jQuery Plugin with this update! jQuery Push API

There are more behind the scenes updates that you get for free! Play around with the on-page test buttons: JavaScript Push API 2.0 Tutorial Updates

]]>
<![CDATA[jQuery Push API]]> http://www.pubnub.com/blog/jquery-push-api

jQuery Push API

June 17th, 2010 The new PubNub JavaScript Push API 2.0 now with jQuery Plugin! If you are a jQuery user and have wanted a Push API with Publish and Subscribe, then hurray! Here is the fastest and lightest jQuery Push API. It is compatible with mobile phone devices such as iPhone, iPad, Blackberry, Android, Symbian and more.

jQuery with PubNub JavaScript Push API 2.0

jQuery Push API provides Comet based Publish and Subscribe real time messaging. It offers the functions available to the PubNub JavaScript Push API. The following are the two most common functions:

jQuery Comet Subscribe

// jQuery.PUBNUB.subscribe( args, callback )
jQuery.PUBNUB.subscribe({
    channel : 'my_channel'
}, function(message) {
    // Show Message
    console.log(message);
} );

jQuery Comet Publish

// jQuery.PUBNUB.publish( args, callback )
jQuery.PUBNUB.publish( {
    channel : 'my_channel',
    message : { 'my_var' : 'some text data' }
});

Download JavaScript Push API

When using PubNub with jQuery, place jQuery script before PubNub. This way you will earn the jQuery.PUBNUB object namespace. Read Updated API 2.0 Doc for full list of functions: JavaScript Push API 2.0 Tutorial Updates

Visit jQuery website for additional details: jQuery Push API

]]>
<![CDATA[JavaScript Push API]]> http://www.pubnub.com/tutorial/javascript-push-api
WANRING: This content is OLD!

JavaScript API Advanced

The PUBNUB object is a Publish + Subscribe Push Framework for JavaScript.

Download JavaScript Push API

PubNub is designed for developers and businesses that have event-driven needs within their applications and games that require a flexible, reliable, cost-effective messaging solution that can scale seamlessly. It is a web service that makes it easy to set up, operate, and send notifications from the cloud. PubNub can be highly customized by developers to meet a wide range of application needs. PubNub allows applications and end-users on different devices to receive notifications instantly.

Developers can get started by using just two APIs: PUBNUB.subscribe(), and PUBNUB.publish(). All messages instantly become compressed JSON. PubNub is designed to meet the needs of the largest and most demanding applications and games, allowing an unlimited number of messages published at any time. PubNub provides interface mechanisms to ensure that messages are secured against unauthorized access. Developers can chose to restrict who can publish or subscribe. APIs available in JavaScript, iPhone, Android, Flash, Ruby, Python and more which all deliver bidirectional Real-time messaging service in the cloud.

This is the Advanced PubNub 3.0 JavaScript Real-time Cloud Push API turorial. To start with a basic intro, read the PubNub Developer Intro Tutorial Hello World.

Compatibility

iPhone, iPad, Android, BlackBerry, Windows, Symbian. FireFox, Safari, Opera, Chrome, Flock, IE. Cross Browser, Cross Domain, Mobile.

Subscribe

    // PUBNUB.subscribe( options )
    PUBNUB.subscribe({
        channel  : "my_channel",
        callback : function(message) { console.log(message) },
        error    : function(e) {
            // Do not call subscribe() here!
            // PUBNUB will auto-reconnect.
            console.log(e);
        }
    });


* Open FireBug Console for More Info

Publish

    // PUBNUB.publish( options )
    PUBNUB.publish({
        channel  : "my_channel",
        message  : "Hello World",
        callback : function(info) {

            // info[0] == 1 for success
            // info[0] == 0 for failure

            // info[1] == "D" for "Demo Success" or
            // info[1] == "S" for "Success with Valid Key" or
            // info[1] == "Error..." with reason of failure.

            // if the respons is an error, do not re-publish.
            // the failed publish will not re-send.

            console.log(info);
        }
    });


* Remember to TEST PUBNUB.subscribe() first

Additional functions for your application. UnSubscribe is available in PubNub JavaScript Push API Use the History command to recall previous messages published. UUID for generating a Universally Unique ID. Use the Time function for synchronized time around the globe.

Unsubscribe

    // PUBNUB.unsubscribe( options )
    PUBNUB.unsubscribe({ channel : 'my_channel' });

History

    // PUBNUB.history( options, callback )
    PUBNUB.history( {
        channel : 'my_channel',
        limit   : 10
    }, function(messages) {
        // Shows All Messages
        console.log(messages);
    } );


* Remember to TEST PUBNUB.publish() first!
* Open Console for More Info

UUID

    // PUBNUB.uuid( callback )
    PUBNUB.uuid(function(uuid) {
        console.log(uuid);
    });

Time

    // PUBNUB.time( callback )
    PUBNUB.time(function(time) {
        console.log(time);
    });

DOM + PUBNUB

The following provide the fastest possible access to the DOM. Focus is on performance and simplicity. Anti-jQuery syntax provides increased performance; especially on mobile phones. However, feel free to use jQuery and other libraries with PUBNUB.

jQuery-style $

    // PUBNUB.$(id)
    var html_node = PUBNUB.$('id-of-html-element');
    var some_div  = PUBNUB.$('some-div');
    

Bind

    // PUBNUB.bind( type, node, callback )
    PUBNUB.bind(
        'click',
        PUBNUB.$('id-of-html-element'),
        function(element) {
            console.log('clicked');
            console.log(element);
        }
    );

    PUBNUB.bind(
        'mousedown',
        PUBNUB.$('some-div'),
        function(element) {
            console.log('clicked');
        }
    );

Search

    // PUBNUB.search(element_type)
    var all_divs  = PUBNUB.search('div');
    var all_links = PUBNUB.search('a');

Attr

    // PUBNUB.attr( node, attribute, value )

    var node = PUBNUB.$('some-div-id');

    // Get
    var href = PUBNUB.attr( node, 'href' );
    // Set
    PUBNUB.attr( node, 'href', '/blog' );

CSS

    // PUBNUB.css( node, styles )
    PUBNUB.css( PUBNUB.$('some-div-id'), {
        top   : 100,
        left  : 100,
        color : "#ff0000"
    } );

Supplant

    // PUBNUB.supplant( template, data )
    var text = PUBNUB.supplant( 'Hello {name}!', { name : 'John' } )
    // Hello John!

There are only two functions you need to know: Publish() and Subscribe(). JavaScript Push API focuses on speed and usability.

Click to see your JS Include
]]>
<![CDATA[Fastest JavaScript Google Closure + gzip -9 + Memcache + CDN + Headers]]> http://www.pubnub.com/blog/fastest-javascript-google-closure-gzip-9-memcache-cdn

Fastest JavaScript Google Closure + gzip -9 + Memcache + CDN + Headers

June 11th, 2010 At PubNub we use Google Closure Advanced Optimizations Mode, Max Gzipping -9 and Memcache for best possible performance delivery of our JavaScripts.

Closure + gzip -9 and Memcache

Research, Benchmarks and Stress Tests has lead to create the best JavaScript delivery method to date. If you are looking for today's best method for JavaScript Compression and Performance Delivery methods, then you are in the right place today.

To squeeze the fast juice from our networks we did the following:

  1. JavaScript File: "code.js"
  2. Run Google Closure Advanced (requires code fixes)
  3. Gzip with max compression (gzip -9)
  4. Memcache this file (or APC if using PHP)
  5. If a CDN is in your budget, use this instead.
  6. If using Google App Engine, you get both Memcache+CDN!

Also modify headers to a set of FOUR. Make sure there are no more than FOUR because headers are uncompressed.

  1. 'Content-Type' = 'text/javascript'
  2. 'Content-Length' = 1234
  3. 'Conent-Encoding' = 'gzip'
  4. 'Expires' = 'Wed, 01 Jan 2025 16:00:00 GMT'

Also consider adding Proxy Cache-Control header for extra chances of cached data on a local box for people who live in remote regions.

To test the amount of juice that can be sqeezed, run the following command:

    java -jar compiler.jar \
        --compilation_level ADVANCED_OPTIMIZATIONS \
        --js code.js \
        | gzip -c9 \
        | wc -c

This command will report a total byte count which tells the payload size. Under 4,000 bytes is the goal. Our PUBNUB Library is under 2,900 bytes.

You'll want to grab Closure Compiler if you don't yet have it. Download Google Closure Compiler

Visit the Google Closure Compiler website for full documentation.

Google Closure Compiler Advanced

To start, running Google Closure in Advanced Mode requires you to specify which object descendants must not be reduced to a single letter ('object.apple' to 'o.a').

These are important to identify especially if JSON + AJAX is invovled. JSON accessed by the compiled code is not referencable.

The Solution is to wrap the descendants name with ['some_val']

my_obj['some_val'] = m.some_val

Otherwise this will happen:

my_obj.some_val = m.s

Now you can safely execute Google Closure Compiler with Advanced Optimizations.

    java -jar compiler.jar \
        --compilation_level ADVANCED_OPTIMIZATIONS \
        --js code.js > code.min.js

Google App Engine CDN

Since GAE is acting as a CDN, you can use the Memcache APIs to store your compiled goodness. This saves GAE from looking up the file in their crazy file system. Here is the script we use to provide GAE and our other Servers with fully optimized JavaScript deliverability:

    java -jar compiler.jar \
        --compilation_level ADVANCED_OPTIMIZATIONS \
        --js code.js \
        | gzip -c9 \
        | send-optimized.sh

send-optimized.sh has every server IP and access key for ssh access. Or in the case of GAE, a secure custom delivery API.

CDN Other than Google

If you are using another CDN, you'll need to forget about the memcache step listed above. However choosing a CDN over Memcache is much better especially if your audience is international. Your send-optimized.sh script will instead deliver the gzipped file to your CDN gateway.

Fast is Important

Page delivery speed is crucial and has direct correlation with revenue. In the case of Google, adding only 100ms to each page request drops revenue several percent. That will be a large number for Google.

Take into account all the mobile users and growing network congestions. Slow network speeds can be improved by following Closure + Gzip + Memcache + CDN + Header changes.

Don't forget international! With all these Optimizations, your friends in other countries can enjoy a speedy web experience too.

You can do the same with CSS! CSS3 Performance Optimizations

]]>