0
0
Expressframework~5 mins

Emitting and receiving messages in Express

Choose your learning style9 modes available
Introduction

Emitting and receiving messages lets your server and clients talk to each other in real time. This helps build interactive apps like chat or live updates.

You want to send a chat message from one user to others instantly.
You need to update a dashboard live when data changes on the server.
You want to notify users immediately when a new event happens.
You want to build a multiplayer game where players see moves live.
You want to sync data between multiple clients without refreshing.
Syntax
Express
socket.emit(eventName, data)
socket.on(eventName, callback)

socket.emit sends a message with a name and data.

socket.on listens for messages with that name.

Examples
Sends a chat message to the server or other clients.
Express
socket.emit('chat message', 'Hello everyone!')
Listens for chat messages and logs them when received.
Express
socket.on('chat message', (msg) => {
  console.log('New message:', msg)
})
Sample Program

This Express server uses Socket.IO to handle real-time chat messages. When a client sends a 'chat message', the server logs it and sends it to all connected clients.

Express
import express from 'express'
import http from 'http'
import { Server } from 'socket.io'

const app = express()
const server = http.createServer(app)
const io = new Server(server)

app.get('/', (req, res) => {
  res.sendFile(new URL('index.html', import.meta.url).pathname)
})

io.on('connection', (socket) => {
  console.log('A user connected')

  socket.on('chat message', (msg) => {
    console.log('Message received:', msg)
    io.emit('chat message', msg) // send to all clients
  })

  socket.on('disconnect', () => {
    console.log('User disconnected')
  })
})

server.listen(3000, () => {
  console.log('Server listening on http://localhost:3000')
})
OutputSuccess
Important Notes

Make sure to include the Socket.IO client script in your HTML to connect and send/receive messages.

Use unique event names to avoid confusion between different message types.

Remember to handle client disconnects to keep your app stable.

Summary

Emitting sends messages; receiving listens for them.

This helps build live, interactive apps with Express and Socket.IO.

Use clear event names and handle connections carefully.