
- HTML - Home
- HTML - Roadmap
- HTML - Introduction
- HTML - History & Evolution
- HTML - Editors
- HTML - Basic Tags
- HTML - Elements
- HTML - Attributes
- HTML - Headings
- HTML - Paragraphs
- HTML - Fonts
- HTML - Blocks
- HTML - Style Sheet
- HTML - Formatting
- HTML - Quotations
- HTML - Comments
- HTML - Colors
- HTML - Images
- HTML - Image Map
- HTML - Frames
- HTML - Iframes
- HTML - Phrase Elements
- HTML - Code Elements
- HTML - Meta Tags
- HTML - Classes
- HTML - IDs
- HTML - Backgrounds
- HTML Tables
- HTML - Tables
- HTML - Table Headers & Captions
- HTML - Table Styling
- HTML - Table Colgroup
- HTML - Nested Tables
- HTML Lists
- HTML - Lists
- HTML - Unordered Lists
- HTML - Ordered Lists
- HTML - Definition Lists
- HTML Links
- HTML - Text Links
- HTML - Image Links
- HTML - Email Links
- HTML Color Names & Values
- HTML - Color Names
- HTML - RGB & RGBA Colors
- HTML - HEX Colors
- HTML - HSL & HSLA Colors
- HTML - HSL Color Picker
- HTML Forms
- HTML - Forms
- HTML - Form Attributes
- HTML - Form Control
- HTML - Input Attributes
- HTML Media
- HTML - Video Element
- HTML - Audio Element
- HTML - Embed Multimedia
- HTML Header
- HTML - Head Element
- HTML - Adding Favicon
- HTML - Javascript
- HTML Layouts
- HTML - Layouts
- HTML - Layout Elements
- HTML - Layout using CSS
- HTML - Responsiveness
- HTML - Symbols
- HTML - Emojis
- HTML - Style Guide
- HTML Graphics
- HTML - SVG
- HTML - Canvas
- HTML APIs
- HTML - Geolocation API
- HTML - Drag & Drop API
- HTML - Web Workers API
- HTML - WebSocket
- HTML - Web Storage
- HTML - Server Sent Events
- HTML Miscellaneous
- HTML - Document Object Model (DOM)
- HTML - MathML
- HTML - Microdata
- HTML - IndexedDB
- HTML - Web Messaging
- HTML - Web CORS
- HTML - Web RTC
- HTML Demo
- HTML - Audio Player
- HTML - Video Player
- HTML - Web slide Desk
- HTML Tools
- HTML - Velocity Draw
- HTML - QR Code
- HTML - Modernizer
- HTML - Validation
- HTML - Color Picker
- HTML References
- HTML - Cheat Sheet
- HTML - Tags Reference
- HTML - Attributes Reference
- HTML - Events Reference
- HTML - Fonts Reference
- HTML - ASCII Codes
- ASCII Table Lookup
- HTML - Color Names
- HTML - Character Entities
- MIME Media Types
- HTML - URL Encoding
- Language ISO Codes
- HTML - Character Encodings
- HTML - Deprecated Tags
- HTML Resources
- HTML - Quick Guide
- HTML - Useful Resources
- HTML - Color Code Builder
- HTML - Online Editor
HTML - WebSockets
WebSockets is a next-generation bidirectional communication technology for web applications that operates over a single socket.
WebSockets allow bidirectional communication, which means both client and server can send data to each other independently and simultaneously.
After establishing a Web Socket connection with the web server, we can send data from browser to server by calling the send()
method and receive data from server to browser by an onmessage
event handler.
Syntax
Following is the API, which creates a new WebSocket object:
var Socket = new WebSocket(url, [protocol] );
Here the first argument, url
, specifies the URL to which to connect. The second attribute, protocol
, is optional and, if present, specifies a sub-protocol that the server must support for the connection to be successful.
Attributes of WebSocket
Following are the attributes of the WebSocket object. Assuming we created a socket object as mentioned above:
Attribute | Description |
---|---|
Socket.readyState | The readonly attribute readyState represents the state of the connection. It can have the following values:
|
Socket.bufferedAmount | The readonly attribute bufferedAmount represents the number of bytes of UTF-8 text that have been queued using the |
WebSocket Events
Following are the events associated with the WebSocket object. Assuming we created a socket object as mentioned above:
Event | Values & Event Handler | Values & Description |
---|---|---|
open | Socket.onopen | This event occurs when socket connection is established. |
message | Socket.onmessage | This event occurs when client receives data from server. |
error | Socket.onerror | This event occurs when there is any error in communication. |
close | Socket.onclose | This event occurs when connection is closed. |
WebSocket Methods
Following are the methods associated with the WebSocket object. Assuming we created a socket object as mentioned above:
Method | Description |
---|---|
Socket.send() | The send(data) method transmits data using the connection. |
Socket.close() | The close() method would be used to terminate any existing connection. |
Setting Up the WebSocket Server with Python
- Step 1. Install Python
- If you don't have Python installed on your device, download and install it from Python.org
- Step 2. Install WebSocket library
- After installing python create a folder for your project, and open that folder in the command prompt or terminal. Then run this prompt.
pip install websockets
- Step 3. Create the websocket server
- Open any text editor and write the below Python code. Then save that as a file in the folder with the name 'server.py'
import asyncio import websockets async def echo(websocket, path): async for message in websocket: print(f"Received message: {message}") await websocket.send(f"Server: You said \"{message}\"") start_server = websockets.serve(echo, "localhost", 8080) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever()
- Step 4. Run the server
- In the terminal navigate to your project folder, and run this command to start server.
python server.py
Setting up HTML Client for the Server
So far we setup a Python server for websocket. The server will be running on your terminal, so any messages sent to the server will be visible at the terminal. Here we will see how to setup a client that can receive messages from the server and also send messages to the server using HTML and JavaScript.
Create an HTML file 'index.html' in the folder.
<!DOCTYPE html> <html lang="en"> <head> <title>WebSocket Example</title> </head> <body> <h1>WebSocket Client</h1> <input type="text" id="messageInput" placeholder="Type a message..." /> <button id="sendButton"> Send </button> <div id="messages"> </div> <script> const socket = new WebSocket('ws://localhost:8080'); socket.addEventListener('open', () => { console.log('Connected to server'); }); socket.addEventListener('message', (event) => { const messageDiv = document.createElement('div'); messageDiv.textContent = event.data; document.getElementById('messages').appendChild(messageDiv); }); document.getElementById('sendButton').addEventListener('click', () => { const messageInput = document.getElementById('messageInput'); const message = messageInput.value; socket.send(message); messageInput.value = ''; }); </script> </body> </html>