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. 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. 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. 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. 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. 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.” );
};