Skip to content

Server IO Emit

Video Lecture

Server IO Emit Server IO Emit

Description

Emit a message to all connected sockets.

Used most often when a server level event occurs. E.g., a timer event occurred, and you want to send a message to all clients.

img/server-io-broadcast-emit.jpg

./src/server/server.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { createServer } from 'http'
import { Server } from 'socket.io'
import * as express from 'express'
import * as path from 'path'

const port = 3000

const app = express()
app.use(express.static(path.join(__dirname, '../client')))

const server = createServer(app)

const io = new Server(server)

io.on('connection', (socket) => {
  console.log('a user connected : ' + socket.id)

  socket.emit('message', 'Hello ' + socket.id)

  socket.broadcast.emit('message', 'Everybody, say hello to ' + socket.id)

  socket.on('disconnect', () => {
    console.log('socket disconnected : ' + socket.id)

    socket.broadcast.emit('message', socket.id + ' has left the building')
  })
})

server.listen(port, () => {
  console.log('Server listening on port ' + port)
})

setInterval(() => {
  io.emit('message', Math.floor(Math.random() * 100))
}, 1000)

./src/client/client.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { io } from 'socket.io-client'

const socket = io()

socket.on('connect', () => {
  document.body.innerText = 'Connected : ' + socket.id
})

socket.on('message', (message) => {
  document.body.innerHTML += '<p>' + message + '</p>'
  window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' })
})