Rabikant
Posted on November 15th
WebSocket Using NPM - Getting Started Guide
"Lets learn about WebSocket Using NPM"
What is Piesocket?
When using Piesocket, establishing a WebSocket server can easily be done without having to contemplate how the internal support will look like. This is relevant when constructing the testing and development environments and when creating the real-time communication applications that are production-grade.
Please make an account on Piehost.com and grab clusterId and apiKey from there we will need those to connect to PieSocket server.
What is WebSocket?
WebSocket is means of communication that provides a full communication from a browser (or a client) to the server and from the server to the browser over the World Wide Web. It allows for efficient, low-latency, and scalable communication between the client and server, enabling a range of applications that require real-time updates, such as:It provides fast and reliable data transmission between client and server and manages to scale up various applications that may require real time updates such as:
Live Updates: The things that you may share include, shares, prices of shares, scores of basket ball, messages/emails, tweets. Gaming: All games that are multi-player and especially real-time games and all real-time multi- player interaction and all changes in game-state. Chat Applications: Chatting, video and/or screen conferencing. Live Streaming: In the context of video and audio streaming; live events; conferencing, etc., How does WebSocket function?
Here's a high-level overview of the WebSocket protocol:
Handshake: The client will send his HTTP connection request to the server and this connections will contain a headers upgrade. Upgrade: The server comes up with an upgrade request that also includes WebSocker connection establishment. Connection Establishment: The client and server exchange information on the Web Socket, this is a full duplex half connection. Frames: The client and server exchange WebSocket frames which are formed by the actual data that is being transferred. Message: Data passed through WebSockets is divided into frames these frames are then again combined into messages and a message is the highest level of data transfer available in this protocol. Key Benefits of WebSocket
Bi-directional Communication: As the communication between the client and the server is two way and real time, WebSocket is the best for handling large and growing data. Low Latency: There is also low latency for transfer of data in real time meaning, WebSocket is suitable for applications that need frequent and abrupt updates. Real-time Updates: WebSocket helps to make listings highly interactive and undertake changes as close as possible to real time. Scalability: WebSocket is very scalable in terms of connections; thus it can handle a large number of users. Efficient: Fully, WebSocket is more efficient than using normal HTTP requests since it eliminates the multiple HTTP requests and response overhead.
Let's start writing the code
This is an HTML file that sets up a WebSocket connection to a server using JavaScript. Here's a breakdown of the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="ussstf-8">
<title>NodeJS WebSocket</title>
</head>
<body>
<h1>NodeJS WebSocket</h1>
<script>
</script>
</body>
</html>
Document Type Declaration ()
The first line, <! Their parts are as follows; The mandatory statement [DOCTYPE html], is used to declare the document type. It tells the browser that the document being rendered is coded in the HTML5 language. HTML5 is latest version of HTML and this declaration will make the browser render the document in the standard mode.
HTML Element ()
The tag is always the outermost or the root tag of any HTML document out there. The tag is used in every HTML document and the use of more than one tag is prohibited.
Head Element ()
The contains information concerning the document which may include the title of the Web page. The element is placed inside the element and contains the following elements:
Meta Element (): The documents specifics or particularities of the document. The xmlns attribute examines the namespace that is set to http:///www. w3. There is certain attributes of HTML such as the xmlns attribute is developed as http://www.w3.org/1999/xhtml while the charset attribute is meant for declaring the character set of the document that is utf-8. Unicode is universal encoding which can deal character codes with tremendous amount of numbers together with the other more than English language characters and other symbols as ~, @ #, $ etc.
Title Element (NodeJS WebSocket): The element defines the title of the page that is shown in the browser’s title bar and used by search engines as the title of the specific page among the search results. Thus, the title stands as NodeJS WebSocket.</p> <p>Body Element (<body>)</p> <p>It is used for grouping other elements and in fact it is that element that contains the content of the HTML document. This is the centre of the HTML and encompasses all the elements that appear within the browser window.</p> <p>Primary Heading (<h1>NodeJS WebSocket</h1>)</p> <p>The <h1> is one of the heading elements that contains the text in the large font size. In this case, the text is NodeJS WebSocket. Probably, the most known tags which are used for define headings of an HTML document are heading elements, which looks like <h1>, <h2>, etc., and here <h1> is the largest and the most important heading.</p> <p>Script Element (<script></script>)</p> <p>The <script> element is used to insert JavaScript code into an HTML document to either of these stages. JavaScript is a language the same way as Python or Java, although, it is executed by the browser to provide interactivity to a web page. In this case the content between the <script> element is missing, however code written between the <script> tags is recognized and interpreted by the browser differently.</p> <p>Overview</p> <p>Thus, this HTML code generates a simple HTML webpage with a title, a heading that contains the text “Hello world,” and an empty script tag, which can be filled with JavaScript code. The document is in UTF-8 to the improvement of the data type, and the title of the document is NodeJS WebSocket Server. The HTML code follows the HTML basic template in which the document is made of the basic HTML tags. These are DOCTYPE html, html, head, title, body and h1.</p> <p>This HTML code can be used as a foundation of the webpage interacting with a NodeJS WebSocket server. WebSocket is a protocol which enables a two-way real time communication between a client and a server useful for application which require live updates such as game, chat applications and many others.</p> <pre><code class="language-javascript">const ws = new WebSocket("wss://CLUSTER_ID.piesocket.com/v3/ROOM_ID?api_key=API_KEY "); ws.addEventListener("open", () =>{ console.log("Connected to piesocket"); });</code></pre> <p>Line 1: const ws = new WebSocket("wss:URL is: “//CLUSTER_ID. piesocket. com/v3/ROOM_ID?api_key=API_KEY “</p> <p>const ws: Defines ws as a variable of data type constant to represent the WebSocket object.</p> <p>new WebSocket(): Establishes a new WebSocket object which acts as a link with the web server.</p> <p>"wss://CLUSTER_ID. piesocket. com/v3/ROOM_ID?api_key=API_KEY : Here, you will define the endpoint of WebSocket server that is used to establish a connection.</p> <p>Here's a breakdown of the URL:</p> <p>wss: Refers to the implementation of a secure protocol in WebSocket connections, namely WebSocket over SSL/TLS</p> <p>CLUSTER_ID. piesocket. com: This parameter reflects the domain of the Piesocket cluster on the world wide web. Change the value of CLUSTER_ID to the ID of your Piesocket cluster.</p> <p>v3: A parameter indicating that the interaction with the Piesocket API is the v3 version.</p> <p>ROOM_ID: The identification number of the room to enter and/or join. Where ROOM_ID is the actual ID of the room which you wish to connect to.</p> <p>api_key=API_KEY: A parameter that contains a value of the API key and send to the server as part of a query string. Where API_KEY is represented by the actual API key that is obtained from Piesocket.</p> <p>Line 2: ws. open function=addEventListener( “open”,()=>{ console.log(“Connected to piesocket”) });</p> <p>ws. addEventListener(): Sets an event listener on the WebSocket object.</p> <p>"open": The event type to listen for. In this case, the “open” event is fired, as the socket is connected, and the connection object is ready and connected.</p> <p>() =>{ console. log("Connected to piesocket"); }): Function that will be invoked each time ‘open’ event is fired, it is a new arrow function. This function logs a message to the console: Here ‘Connected to piesocket’ indicates that the program is connected with the pie socket through which all the data packets are transmitted.</p> <p>Here's what happens when this code is executed:</p> <p>The WebSocket connection is established with the Piesocket server at wss:It also incorporated the account number into the design, as is evident from the cutting-in of the account number at //CLUSTER_ID. piesocket. com/v3/ROOM_ID.</p> <p>If the connection is successfully created, the “open” event is fired.</p> <p>The event listener function is finally called, and it simply logs “Connected to piesocket” to the console.</p> <p>Piesocket Concepts</p> <p>Cluster: A cluster is a group of WebSocket servers which is a single entry point for WebSocket connections. Each cluster has a specific id which is incorporated to the WebSocket URL.</p> <p>Room: A room is also a place in a cluster where clients can chat and, or exchange messages. It is interesting to note that each of the rooms has its ID which is appended to the WebSocket address.</p> <p>API Key: API key on Piesocket is a secret token that gives permissions to the WebSocket connection.</p> <p>This is the whole code you can paste this in index.html</p> <pre><code class="language-html"><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>NodeJS WebSocket Server</title> </head> <body> <h1>Hello world</h1> <script> const ws = new WebSocket("wss://free.blr2.piesocket.com/v3/1?api_key=B9UKgvptNTWrZxfCUTquFp7nKVsYqu2LtmBao5Jg"); ws.addEventListener("open", () =>{ console.log("Connected to piesocket"); }); </script> </body> </html></code></pre>
