HTML5WS

From mi-linux
Jump to navigationJump to search

Main Page >> Advanced Web Technologies >> Workbook >> Week 06 - HTML5 Web Sockets

HTML5 Web Sockets

This page features the full code of the following webpage: http://mi-linux.wlv.ac.uk/~in9352/websockets/

In order to avoid having to set-up a web socket service on the server, we are using this free, cloud-based web socket API:

The free Sandbox plan includes up to 20 connections and 100,000 messages per day. Both client-side and server-side libraries are provided, so we won't need to write much code at all!

index.html

The webpage itself is using the brand new HTML5 Document type, as well as a couple of HTML5 new features:

  • New semantic elements, e,g, header, section, footer
  • New placeholder attribute for the text boxes

It links to a simple stylesheet (see code further down), as well as 3 JavaScript files:

  • pusher.js - the client-side library to access the cloud-based Web Socket API
  • jquery - to facilitate DOM manipulation and Ajax requests.
  • websockets.js - our own JavaScript code (we still need to write some!)
<!DOCTYPE HTML>
<html>
  <head>
    <title>Share a happy thought</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    
    <link rel="stylesheet" type="text/css" href="css/style.css" />
    <script src="http://js.pusher.com/2.1/pusher.min.js"></script>
    <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
    <script src="js/websockets.js"></script>
  </head>
  <body>
    <header>
      <h1>Share a happy thought</h1>
      <p>An idea, a saying, a funny quote, a link... anything!</p>
    </header>
    <section id="new-message">
      <form>
        <input type="text" id="yourname" placeholder="Your name">
        <input type="text" id="yourmessage" placeholder="Your happy thought">
        <input type="button" id="postit" value="Post">
        <span id="debugmessage"></span>
      </form>
    </section>
    <section id="messages"></section>
    <footer>
      Powered by 
      <a href="http://www.html5rocks.com/en/">HTML5</a>, 
      <a href="http://dev.w3.org/html5/websockets/">Web Sockets</a>, 
      <a href="http://pusher.com/">Pusher</a>, 
      <a href="http://jquery.com/">JQuery</a> and 
      <a href="http://www.css3.info/">CSS3</a>. 
      Copyright 2011 by Alix Bergeret. All Rights Reserved.
    </footer>
  </body>
</html>

css/style.css

Nothing major here, aside from some nice CSS3 effects!

@font-face 
{
  font-family: alix;
  src: url('../fonts/Bubblegum.ttf');
}

a, a.visited, p, header,footer, input, span  
{
  font-family: Arial
}

body
{
  background-color: #E0E0E0
}

a, a.visited
{
  color: #FFBF00;
}

span#debugmessage
{
  font-size: small
}

header,footer    
{
  background-color: #4F4FD9;
  text-align: center;
  padding: 10px;
  margin: 10px;
  color: #FFBF00;
  
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  border-radius: 10px;  
  
  -webkit-box-shadow: 5px 5px 5px 0px #000000;
  -moz-box-shadow: 5px 5px 5px 0px #000000;
  box-shadow: 5px 5px 5px 0px #000000;  
  
  
  background: rgb(115,115,217); /* Old browsers */
  background: -moz-linear-gradient(left, rgba(115,115,217,1) 0%, rgba(79,79,217,1) 100%); /* FF3.6+ */
  background: -webkit-gradient(linear, left top, right top, color-stop(0%,rgba(115,115,217,1)), color-stop(100%,rgba(79,79,217,1))); /* Chrome,Safari4+ */
  background: -webkit-linear-gradient(left, rgba(115,115,217,1) 0%,rgba(79,79,217,1) 100%); /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(left, rgba(115,115,217,1) 0%,rgba(79,79,217,1) 100%); /* Opera11.10+ */
  background: -ms-linear-gradient(left, rgba(115,115,217,1) 0%,rgba(79,79,217,1) 100%); /* IE10+ */
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#7373d9', endColorstr='#4f4fd9',GradientType=1 ); /* IE6-9 */
  background: linear-gradient(left, rgba(115,115,217,1) 0%,rgba(79,79,217,1) 100%); /* W3C */
  
}

header
{
  font-family: alix;
  font-size: x-large;
  text-shadow: 3px 3px 3px #000000;
  filter: dropshadow(color=#000000, offx=3, offy=3);
}

footer
{
  font-size: small;
}

p
{
font-size: large;
}

#new-message
{
  margin: 10px 20px 5px 20px
}
#yourmessage
{
  width: 300px
}

#messages
{
  height: 200px;
  background-color: #ffffff;
  overflow-y: scroll;
  overflow-x: hidden;
  margin: 10px;
  padding: 10px;
  border: 1px black solid;
  
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  border-radius: 10px;    
}

js/websockets.js

Because we are using the provided client-side Pusher library, we don't need to write too much JavaScript code... here it is!

// Make connection when DOM has finished loading
$(document).ready(ConnectToChat);
//------------------------------------------------------------------------------
function ConnectToChat()
{
// Open connection 
$('#postit').attr('disabled', 'disabled');
$('#debugmessage').text('Connecting...');


// ### My Pusher credentials, get your own!###
$key = 'Type Here';
$secret = 'Type Here';
$app_id = 'Type Here';
var pusher = new Pusher($key, $secret, $app_id);

// Check connection status
pusher.connection.bind('connected', function()
{
$('#postit').removeAttr('disabled');
$('#debugmessage').text('Connected!').fadeOut(2000);
});

// Create channel 
var myChannel = pusher.subscribe('chat-channel'); 

// Bind event to function
myChannel.bind('new-message', 
function(data) 
{
$('#messages').append(data);
$("#messages").prop({ scrollTop: $("#messages").prop("scrollHeight") });
});

// Bind enter key to post message
$('#yourmessage').bind('keypress', function(e) {
if(e.keyCode==13){
SendNewMessage();
}
});

// Bind button click to post message
$('#postit').click(SendNewMessage);

}

//------------------------------------------------------------------------------
function SendNewMessage()
{
// Read name and message from form 
var name = $('#yourname').val();
var message = $('#yourmessage').val();
var connecting = $('#postit').prop('disabled');

// Validate input
if(name=='')
name="Anonymous";

// Are we still connecting?
if(connecting)
exit;

if(message!='')
{
// Clear message
$('#yourmessage').val('');

// Send message to server
$.ajax({
// ### Your URL Here StudentNo/YourFilesFolder/push-event.php ###
url: "http://mi-linux.wlv.ac.uk/~0000000/myHTML5Folder/push-event.php",
type: "POST",
data: ({name : name, message : message, key : $key, secret : $secret, app_id : $app_id})
});
}

// Refocus on text input ready for next message 
$('#yourmessage').focus();

}

When a user posts a message we use JQuery to sent an Ajax request to the push-event.php file... see below!

push-event.php

This time we are using the provided server-side Pusher library (Pusher.php), so again not too much for us to do!

<?php
require('Pusher.php');

// Read and clean user input
$message = CleanInput($_POST['message']);
$name = CleanInput($_POST['name']);

// Handles ID etc 
$key = $_POST['key'];
$secret = $_POST['secret'];
$app_id = $_POST['app_id'];

// Create pusher object
$pusher = new Pusher($key, $secret, $app_id);

// Trigger new-message event, which will be sent to all clients
$pusher->trigger('chat-channel', 'new-message', $name.' says: '.$message.'<br />');

//------------------------------------------------------------------------------

function CleanInput($text) 
{
$text = stripslashes($text);
$text = htmlentities($text);
$text = preg_replace('/https?:\/\/[^\s<]+/i', '<a href="\0">\0</a>', $text);

return $text;
}
?>