Web sockets Introduction

544 views

Published on

An introduction to WebSockets using Javascript.

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
544
On SlideShare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
8
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Web sockets Introduction

  1. 1. Web Sockets
  2. 2. What is it…?• At the simplest terms, “an advanced technology that allows an interactive communication between browser & server”• Perform real-time communication instead of having to poll server for reply.• An Event-driven API.
  3. 3. Creating a Web Socket• For communicating using Web Socket, we need to create a Web Socket object, which will try to open connection to the server.• Example:: //open socket var helloSocket = new WebSocket("ws://localhost:8000/socket/daemon.php"); //connection states helloSocket.readyState == CONNECTING; //its getting connected helloSocket.readyState == OPEN; //connection ready for data transfer
  4. 4. Sending Data to Server• Data can be transmitted to the server by simply calling send() method of WebSocket object, like so: //data can be sent as String, Blob or ArrayBuffer //check if socket is opened, if it is, send the data helloSocket.onopen = function() { helloSocket.send(“Hi there, this is from some client browser.”); );
  5. 5. Sending Data to Server• JSON can also be used to send complex data to the server, like: //create object var myMessage = { msg_type : “some_type”, msg_text : “this is a message from client”, msg_date : Date.now() }; //send the message object helloSocket.onopen = function() { helloSocket.send( JSON.stringify(myMesage) ); };
  6. 6. Receiving Data from Server• Listening for incoming data is also simple, calling “onmesage” event does the job. //Example helloSocket.onmessage = function( event ) { console.log( event.data ); // here’s message from server }; Note-: Data received over a WebSocket connection is UTF-8 formatted.
  7. 7. Finally, closing the connection• Calling WebSocket’s close() method closes the connection.• Before calling the “close()” method, its generally a good idea to check for socket’s bufferedAmount attribute, to check if any data is yet to be transferred, which can be checked doing:: helloSocket.bufferedAmount  number of bytes that has been queued helloSocket.onclose = function() { console.log( “socket connection closed.” ); };
  8. 8. That’s ItThanks for reading…!

×