Kode Blog - Inspiring And Empowering Developers.
A WebSocket API is an Application Programming Interface that enables web pages to use the WebSockets protocol for two-way communication with a remote host.
If you are familiar with object oriented programming then using the WebSocket will be very easy for you.
These are the attributes of the websocket class.
0this is the default value. It means the connection has not been established to the server.
1This value means the connection to the server has been established and it is ready for communication.
2This value means the connection is closing.
3This value means the connection has being closed. It is also used when the connection fails to open.
Sendthis method is used to transmit data to the server after a connection has been successfully established.
Closethis method is used to close an active connection to the server.
onopenthis is the event that is called when a connection to the server has been successfully created. In other words, it is fired when the
onmessagethis is the event that is called when data is received from the server on the client side.
onerrorthis is the event that is called when any error occurs
onclosethis is the event that is called when the connection to the server has been successfully closed. In other words, it is fired when the
Now that we have covered the basics of the WebSocket, let’s create a basic application that checks if the web browser you are using supports WebSockets or not. Older browsers do not support HTML5 and websockets, the application we are about to build comes in handy before you start executing any code that uses WebSockets.
The following flowchart illustrates the logical flow of the program
Create a learning folder on your computer
Create a file named
websocket_support.html in it
Add the following source code to the file
<script>…</script>contains the Java script code
function WebSocketSupport()is the function that checks if the browser supports websockets
if ("WebSocket" in window)is the code that checks if the WebSocket is available in the window. It returns true if WebSocket is found in the window and false if it is not found.
WebSocketSupportfunction using the body’s
onloadevent. This event is fired when the page loads.
div in the body section depending on the value of the condition.
Testing our application
websocket_support.html in your browser.
Internet Explorer 9 – Does not support WebSockets
Firefox 26 - Supports Web Sockets
Google Chrome 32 – Supports Web Sockets
Tutorial version 1: Date Published 2015-08-20