This is a basic chat example. The code to the left, you can build real-time chat in 10 lines of JavaScript - just copy and paste the code into your favorite text editor and save as a .html.
Enter Chat and press enter <div><input id=input placeholder="message" /></div> Chat Output <div id=box></div> <script src=https://cdn.pubnub.com/sdk/javascript/pubnub.4.28.2.min.js></script> <script> (function() { var pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo' }); function $(id) { return document.getElementById(id); } var box = $('box'), input = $('input'), channel = '10chat-demo'; pubnub.addListener({ message: function(obj) { box.innerHTML = ('' + obj.message).replace(/[<>]/g, '') + '<br>' + box.innerHTML } }); pubnub.subscribe({ channels: [channel] }); input.addEventListener('keyup', function(e) { if ((e.keyCode || e.charCode) === 13) { pubnub.publish({ channel: channel, message: input.value, x: (input.value = '') }); } }); })(); </script>
Tasks like sending and receiving data through PubNub take a single function call. The basic “send” functionality happens through a publish() call.
And to “receive” all of the sent messages on a specific channel, simply make a subscribe() call. All of the network infrastructure and scaling is taken care of for you, so you spend time building your app, not the infrastructure.
// Send a message pubnub.publish({ channel : 'chat', message : "hello!" })
pubnub.addListener({ message: function(msg) { console.log("got a message",msg.message); } }); pubnub.subscribe({channels:['chat']});
PubNub empowers you to build cross-platform, supporting chat for mobile, browser, desktop, server, and even the Internet of Things. Build in one language, extend to every device!
Need help? Contact PubNub Support.