Skip to content

Client Emit

Video Lecture

Client Emit Client Emit

Description

It is also possible, for the client to initiate a message to the server at any time. In this example, we will prompt the client for a username, and then pass it to the server.

./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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { createServer } from 'http'
import { Server } from 'socket.io'
import * as express from 'express'
import * as path from 'path'
import LuckyNumbersGame from './luckyNumbersGame'

const port = 3000

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

const server = createServer(app)

const io = new Server(server)

const game = new LuckyNumbersGame()

const players: { [id: string]: { luckyNumber: number; socketId: string } } = {}

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

  socket.on('joining', (uName) => {
    if (players[uName]) {
      // existing player. Use the lucky number already registered
      players[uName].socketId = socket.id // update the reference since each new connection gets a new socket.id
      socket.emit(
        'joined',
        'Hello "' +
          uName +
          '", welcome back, your lucky number is ' +
          players[uName].luckyNumber
      )
    } else {
      // Create a new player with a new lucky number
      players[uName] = {
        luckyNumber: Math.floor(Math.random() * 20),
        socketId: socket.id
      }

      socket.emit(
        'joined',
        'Hello new player named "' +
          uName +
          '", your lucky number is ' +
          players[uName].luckyNumber
      )
    }

    game.LuckyNumbers[socket.id] = players[uName].luckyNumber

    socket.broadcast.emit('message', 'Everybody, say hello to "' + uName + '"')
  })

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

    const player = Object.keys(players).find((p) => {
      return players[p].socketId === socket.id
    })
    if (player) {
      socket.broadcast.emit('message', 'Player "' + player + '" has left the building')
    }
  })
})

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

setInterval(() => {
  const randomNumber = Math.floor(Math.random() * 20)
  const winners = game.GetWinners(randomNumber)
  if (winners.length) {
    winners.forEach((w) => {
      io.to(w).emit('message', '*** You are the winner with ' + randomNumber + ' ***')
    })
  }
  io.emit('message', randomNumber)
}, 1000)

./src/client/client.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
import { io } from 'socket.io-client'

const socket = io()

let joined = false

socket.on('connect', () => {
  const uName = prompt('What is your name?') // as string
  if (uName) {
    socket.emit('joining', uName)
  }
})

socket.on('disconnect', (message) => {
  alert('Disconnected from Server \nReason : ' + message)
})

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

socket.on('joined', (message) => {
  document.body.innerHTML = '<p>' + message + '</p>'
  joined = true
})