HTML WebSocket
What is WebSocket?
WebSocket is a communication protocol that provides full-duplex (two-way) communication between client and server in real-time.
Basic Syntax
let socket = new WebSocket("wss://example.com/socket");
Example
<button onclick="sendMessage()">Send Message</button>
<p id="status"></p>
<script>
let socket = new WebSocket("wss://echo.websocket.org");
socket.onopen = function(){
document.getElementById("status").innerHTML = "Connected";
socket.send("Hello Server");
};
socket.onmessage = function(event){
document.getElementById("status").innerHTML = event.data;
};
</script>
Where WebSockets are Used?
- Chat applications
- Live notifications
- Online games
- Live trading apps
- Real-time dashboards
Important Note
WebSocket keeps connection open, unlike HTTP which closes after each request.
Security Tip
Always use wss:// (secure WebSocket) instead of ws:// in production.