Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to use sockets in JavaScriptHTML?
To enable bidirectional communication between web applications and server-side processes, JavaScript provides the WebSocket API. Unlike traditional HTTP requests, WebSockets maintain a persistent connection allowing real-time data exchange in both directions.
WebSockets are commonly used for chat applications, live notifications, real-time gaming, stock price updates, and collaborative editing tools where instant communication is essential.
Syntax
Following is the syntax to create a WebSocket connection −
const socket = new WebSocket(url [, protocols]);
Where url is the WebSocket server URL (starting with ws:// or wss://) and protocols is an optional string or array of protocol names.
WebSocket Methods and Properties
The WebSocket object provides several methods and properties for managing connections −
Creating a Connection
const socket = new WebSocket('ws://localhost:8080');
Sending Data
socket.send(data);
Closing the Connection
socket.close([code], [reason]);
Getting Connection URL
socket.url // Returns the WebSocket URL
WebSocket Events
WebSockets trigger events during different stages of the connection lifecycle −
onopen − Triggered when the connection is established
onmessage − Triggered when data is received from the server
onclose − Triggered when the connection is closed
onerror − Triggered when an error occurs
Basic WebSocket Example
Following example demonstrates a complete WebSocket implementation with connection management and message handling −
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Basic Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>WebSocket Communication</h2>
<div id="status">Disconnected</div>
<div id="messages" style="border: 1px solid #ccc; height: 200px; padding: 10px; margin: 10px 0; overflow-y: auto;"></div>
<input type="text" id="messageInput" placeholder="Enter message" style="width: 70%;">
<button onclick="sendMessage()">Send</button>
<button onclick="connectSocket()">Connect</button>
<button onclick="disconnectSocket()">Disconnect</button>
<script>
let socket;
function connectSocket() {
// For demo purposes, we'll simulate a WebSocket connection
// In real applications, use: socket = new WebSocket('ws://localhost:8080');
document.getElementById('status').innerHTML = 'Connecting...';
// Simulate connection success after 1 second
setTimeout(() => {
document.getElementById('status').innerHTML = 'Connected to WebSocket';
document.getElementById('status').style.color = 'green';
addMessage('Connected to WebSocket server');
}, 1000);
}
function sendMessage() {
const input = document.getElementById('messageInput');
const message = input.value.trim();
if (message) {
addMessage('You: ' + message);
// In real WebSocket: socket.send(message);
// Simulate server response
setTimeout(() => {
addMessage('Server: Echo - ' + message);
}, 500);
input.value = '';
}
}
function disconnectSocket() {
// In real WebSocket: socket.close();
document.getElementById('status').innerHTML = 'Disconnected';
document.getElementById('status').style.color = 'red';
addMessage('Disconnected from server');
}
function addMessage(message) {
const messagesDiv = document.getElementById('messages');
messagesDiv.innerHTML += '<div>' + new Date().toLocaleTimeString() + ': ' + message + '</div>';
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
// Allow Enter key to send messages
document.getElementById('messageInput').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
sendMessage();
}
});
</script>
</body>
</html>
This example creates a chat-like interface where you can connect to a WebSocket server, send messages, and receive responses. The status indicator shows the connection state −
WebSocket Communication Connected to WebSocket (in green) [Message area showing timestamped messages] [Enter message] [Send] [Connect] [Disconnect]
Real WebSocket Implementation
Following example shows the actual WebSocket API usage with proper event handlers −
<!DOCTYPE html>
<html>
<head>
<title>Real WebSocket Implementation</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>WebSocket API Implementation</h2>
<div id="connectionInfo" style="margin: 10px 0;"></div>
<div id="output" style="border: 1px solid #ddd; padding: 10px; height: 200px; overflow-y: auto; background: #f9f9f9;"></div>
<button onclick="testWebSocket()">Test WebSocket Connection</button>
<script>
function testWebSocket() {
const output = document.getElementById('output');
const info = document.getElementById('connectionInfo');
output.innerHTML = '';
info.innerHTML = 'Testing WebSocket connection...';
try {
// Note: This will fail in demo as no WebSocket server is running
// Replace with your actual WebSocket server URL
const socket = new WebSocket('wss://echo.websocket.org/');
// Connection opened
socket.onopen = function(event) {
info.innerHTML = 'Connected to: ' + socket.url;
info.style.color = 'green';
output.innerHTML += '<div>? WebSocket connection opened</div>';
// Send a test message
socket.send('Hello WebSocket Server!');
output.innerHTML += '<div>? Sent: Hello WebSocket Server!</div>';
};
// Listen for messages
socket.onmessage = function(event) {
output.innerHTML += '<div>? Received: ' + event.data + '</div>';
};
// Connection closed
socket.onclose = function(event) {
if (event.wasClean) {
output.innerHTML += '<div>? Connection closed cleanly (code=' + event.code + ')</div>';
} else {
output.innerHTML += '<div>? Connection died</div>';
}
info.innerHTML = 'Disconnected';
info.style.color = 'red';
};
// Handle errors
socket.onerror = function(error) {
output.innerHTML += '<div style="color: red;">? WebSocket error: ' + error.message + '</div>';
info.innerHTML = 'Connection failed';
info.style.color = 'red';
};
// Close connection after 3 seconds for demo
setTimeout(() => {
if (socket.readyState === WebSocket.OPEN) {
socket.close(1000, 'Demo completed');
}
}, 3000);
} catch (error) {
output.innerHTML = '<div style="color: red;">Error creating WebSocket: ' + error.message + '</div>';
info.innerHTML = 'Failed to create WebSocket';
info.style.color = 'red';
}
}
</script>
</body>
</html>
This example demonstrates the complete WebSocket lifecycle including connection, messaging, and error handling. The test uses a public echo server for demonstration.
WebSocket Connection States
WebSocket connections have different ready states that can be checked using the readyState property −
| Constant | Value | Description |
|---|---|---|
| CONNECTING | 0 | Connection is being established |
| OPEN | 1 | Connection is open and ready for communication |
| CLOSING | 2 | Connection is in the process of closing |
| CLOSED | 3 | Connection is closed or could not be opened |
Example − Checking Connection State
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Connection States</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>WebSocket Ready State Monitor</h2>
<div id="stateDisplay" style="font-size: 18px; margin: 20px 0;">Ready State: Not Connected</div>
<button onclick="checkConnectionState()">Check Connection State</button>
<div id="stateInfo" style="margin: 20px 0;"></div>
<script>
function checkConnectionState() {
const display = document.getElementById('stateDisplay');
const info = document.getElementById('stateInfo');
// Simulate different connection states
const states = [
{ name: 'CONNECTING', value: 0, description: 'Connection is being established' },
{ name: 'OPEN', value: 1, description: 'Connection is open and ready for communication' },
{ name: 'CLOSING', value: 2, description: 'Connection is in the process of closing' },
{ name: 'CLOSED', value: 3, description: 'Connection is closed or could not be opened' }
];
// Randomly select a state for demonstration
const randomState = states[Math.floor(Math.random() * states.length)];
display.innerHTML = 'Ready State: ' + randomState.name + ' (' + randomState.value + ')';
info.innerHTML = '<strong>Description:</strong> ' + randomState.description;
// Set color based on state
switch(randomState.value) {
case 0:
display.style.color = 'orange';
break;
case 1:
display.style.color = 'green';
break;
case 2:
display.style.color = 'orange';
break;
case 3:
display.style.color = 'red';
break;
}
}
</script>
</body>
</html>
This example demonstrates how to check and display different WebSocket connection states. In real applications, you would check socket.readyState to determine the current connection status.
