πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

WebSockets

Web Foundations🟒 Free Lesson

Advertisement

WebSockets

Real-time communication, bidirectional messaging, and live updates.

Overview

WebSockets enable real-time bidirectional communication.

Key Concepts

  • WebSocket API β€” Browser API for connections
  • Connection Lifecycle β€” Open, message, close, error
  • Bidirectional β€” Server and client can send
  • Binary Data β€” Send binary and text data
  • Reconnection β€” Handle disconnections

Code Examples

<div id="messages"></div>
<input id="messageInput" placeholder="Type a message...">
<button id="send">Send</button>

<script>
const socket = new WebSocket('ws://localhost:8080');
const messages = document.getElementById('messages');

socket.onopen = () => {
  console.log('Connected to server');
  addMessage('System', 'Connected to server');
};

socket.onmessage = (event) => {
  const data = JSON.parse(event.data);
  addMessage(data.sender, data.message);
};

socket.onclose = () => {
  console.log('Disconnected');
  addMessage('System', 'Disconnected from server');
};

socket.onerror = (error) => {
  console.error('WebSocket error:', error);
};

function addMessage(sender, text) {
  const div = document.createElement('div');
  div.innerHTML = `<strong>${sender}:</strong> ${text}`;
  messages.appendChild(div);
  messages.scrollTop = messages.scrollHeight;
}

document.getElementById('send').addEventListener('click', () => {
  const input = document.getElementById('messageInput');
  const message = input.value.trim();
  
  if (message) {
    socket.send(JSON.stringify({ message }));
    addMessage('Me', message);
    input.value = '';
  }
});

document.getElementById('messageInput').addEventListener('keypress', (e) => {
  if (e.key === 'Enter') {
    document.getElementById('send').click();
  }
});
</script>

Practice

Build a real-time chat application with WebSockets.

⭐

Premium Content

WebSockets

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement