📚 Lesson 1: Basic Events

Learn Socket.IO fundamentals: connections, events, and basic communication

🎯 What You'll Learn

In this lesson, you'll understand the core concepts of Socket.IO:

  • How to establish a connection between client and server
  • Basic event emission and listening
  • One-to-one communication patterns
  • Connection status handling

🔑 Key Concepts

  • Socket Connection: A persistent connection between client and server
  • Events: Messages sent between client and server
  • Emit: Sending a message (client → server or server → client)
  • Listen: Receiving a message (using .on() method)
  • Socket ID: Unique identifier for each connection

🔌 Connection Status

Monitor your connection to the Socket.IO server:

Connection Status

Connecting...
Socket ID: Not connected

📤 Sending Your First Message

Learn how to send a message to the server and receive a response:

// Client-side code (what you're using now) socket.emit('hello', { message: 'Hello Server!' }); // Server-side code (running on the server) socket.on('hello', (data) => { console.log('Received:', data.message); socket.emit('hello response', { message: `Server received: ${data.message}`, timestamp: new Date().toISOString() }); });

Try It Out

📥 Receiving Messages

Understanding how to listen for and handle incoming messages:

// Listening for messages from the server socket.on('hello response', (data) => { console.log('Server response:', data); // Handle the response here }); // Listening for connection events socket.on('connect', () => { console.log('Connected to server!'); }); socket.on('disconnect', () => { console.log('Disconnected from server!'); });

Message Log

All incoming messages will appear here:

🔍 Understanding the Code

Let's break down what's happening:

// 1. Create a socket connection const socket = io(); // 2. Listen for connection events socket.on('connect', () => { console.log('Connected!'); }); // 3. Send a message to the server socket.emit('eventName', { data: 'value' }); // 4. Listen for responses from the server socket.on('responseEvent', (data) => { console.log('Received:', data); });

💡 Important Notes

  • Event Names: You can use any string as an event name
  • Data Format: You can send any JSON-serializable data
  • Bidirectional: Both client and server can emit and listen
  • Real-time: Messages are delivered instantly

🎯 Practice Exercise

Try sending different types of messages and observe the responses:

Interactive Testing

💡 Try opening multiple browser tabs to see how each connection gets a unique Socket ID!

✅ What You've Learned

  • ✅ How to establish a Socket.IO connection
  • ✅ How to send messages using socket.emit()
  • ✅ How to receive messages using socket.on()
  • ✅ How to handle connection and disconnection events
  • ✅ Understanding of Socket IDs and event-based communication
Next Lesson: Broadcasting →