onsdagen den 15:e juni 2011

WebSockets Hiby07 work in progress! Here is a new simple WebSocket demo..

It has been a while since I wrote anything here at my blog,  but I suppose that I’m excused? I have been busy with with nice and inspiring things such as Devsum2011 , a fantastic event hosted by Cornerstone.  At DevSum2011 I was given the opportunity to share my thoughts regarding the WebSockets API that’s comes in the wake of HTML5 among a bunch of several other very interesting API.  My session was named The real-time web is here, has AJAX reached the end of the road?

Is this true? Has AJAX really reach the end of the road? NO, is the answer, but our application that relays on our browser will sure change, as well as out view on applications and OS?

So , what do I have in mind?  First of all I want to share some information regarding the WebSocket Server of ours ( UlfBjo’s and mine) called XSocketServer (Working title) , we are now running a beta implementation of Hybi07 ,today only found in Firefox nightly’s?    But!  In this entry I want to share a little thing that uses HTML WebSockets API, FileAPI and the Drag’n drop capabilities of HTML5.

By using those three API’s we are able to let the user drag images from its client (desktop) to the webpage, drop the files on a specific element, read the file and encode it contents as Base64 and broadcast it upon WebSockets; This will give us a very simple “image sharing” application  as shown in the video below.

 

HTML5 FileAPI + WebSockets + Drag’n drop http://bit.ly/jFTou2

Problems viewing; Click here

Here is a brief description of how this was assembled.

The WebSocket Server chosen is as mention above the XSocketServer , that is a competent WebSocket Server running upon the .NET Framework, as shown in earlier post here it can deal both with custom WebSocket Handlers as well as handlers that contains specific logic and methods, in this case we are using the Generic handler, that can be described as follows.

“All messages sent to the socket (WebSocket) is forwarded to each and every connected WebSocket no matter of protocol version or event, it is also send back to the sender itself”

So, this is the JavaScript (using jQuery) as well as HTML5 native stuff, I tried to add some comments to the code and hopefully it is good enough ?

JavaScript.

$(function () {

   
// If we dont have HTML5 Native Drag'n drop , show the file input
    if ('draggable' in document.createElement('span')) {
       
$("#uploadFile").hide();
       
var info = $("<span>").text("Drag and drop image file/files to the box above");
       
$("#info").append(info);

   
} else {
       
var info = $("<span>").text("Choose your image files.. ");

       
$("#info").append(info);
   
}

   
// Enable drag 'n drop, prevent default behavior
    var dropzone = document.getElementById("filelist");

   
dropzone.addEventListener('dragenter', function (e) {
       
e.stopPropagation();
       
e.preventDefault();
   
}, false);

   
dropzone.addEventListener('dragleave', function (e) {
       
e.stopPropagation();
       
e.preventDefault();

   
}, false)
   
dropzone.addEventListener('dragover', function (e) {
       
e.stopPropagation();
       
e.preventDefault();
   
}, false)

   
// When a file/files are dropped, deal with the file/files
    dropzone.addEventListener('drop', function (e) {
       
e.stopPropagation();
       
e.preventDefault();
       
console.log(e);
       
$(e.dataTransfer.files).each(function (i, file) {
           
dealWithFile(file);
       
});
   
}, false);

   
// Create an WebSocket using jXlent (helper)
    var ws = new $$.xWebSocket("ws://127.0.0.1:4502/XSocketSolution.XSocketCommon.Handlers.Generic", jXlent.WEBSOCKET);

   
// When we got a WebSocket connection bind the onFileReadComplete event
    ws.bind("open", function () {
       
console.log("WebSocket is open!");
       
ws.bind("onFileReadComplete", function (file) {
           
$("<img>").addClass("thumbnail").prop("src", file.Base64).appendTo("#recivedImages");
       
});
   
});

   
// If the user select files using the <input type="file"/> element
    $("#uploadFile").change(function () {
       
$(this.files).each(function (i, file) {
           
dealWithFile(file);
       
});
   
});
   
// Deal with the selected or droped file
    function dealWithFile(file) {
       
var reader = new FileReader();
       
reader.onload = (function (readFile) {
           
return function (e) {

               
// Append the file to the UI,show what file we are about to send
                var image = $("<li>").text(readFile.name).appendTo("#files");

               
// Create a WebSocketMessage (WebSocket Event) named onFileReadComplete and attach the data (file) as base64
                var wsbSocketMessage = new $$.WebSocketMessage("onFileReadComplete");

               
wsbSocketMessage.AddJson({
                   
FileName: readFile.name,
                   
Size: readFile.size,
                   
Base64: e.target.result
               
});
               
// Send the WebSocket message
                ws.trigger(wsbSocketMessage.PayLoad());
           
};
       
})(file);
       
// get base64 (Data URI Schema)
        reader.readAsDataURL(file);
   
}

});

The markup is as simple as this.

    <h1>
        HTML5 FileAPI,Drag'n Drop + WebSockets
</h1>
       
<p>
        A simple reatime ImageSharing experience
       
</p>
    
   
<input type="file" id="uploadFile" multiple />
    <
h2>
        My shares
</h2>
   
<div id="filelist">
       
<ul id="files">
       
</ul>
   
</div>
   
<p id="info">
   
</p>
   
<h2>
        All shares
</h2>
   
<div id="recivedImages">
   
</div>

I chosen to to add the CSS to the entry the reason is not much CSS applied at all, so it is not worth to mention.

 

Links:

Enjoy

Magnus Thor

2 kommentarer:

  1. Very, cool demo Magnus! We will have sooo much fun :)

    SvaraRadera
  2. Thanx for the feedback, glad that i could entertain you for a while..

    SvaraRadera