Server IO Emit to Specific Socket
Video Lecture
Description
Using IO to emit a message to a specific socket ID.
./src/server/luckyNumbersGame.ts
1
2
3
4
5
6
7
8
9
10
11
12
13 | export default class LuckyNumbersGame {
public LuckyNumbers: { [id: string]: number } = {}
public GetWinners(number: number): string[] {
const winners = []
for (let id in this.LuckyNumbers) {
if (number === this.LuckyNumbers[id]) {
winners.push(id)
}
}
return winners
}
}
|
./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 | 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()
io.on('connection', (socket) => {
console.log('a user connected : ' + socket.id)
game.LuckyNumbers[socket.id] = Math.floor(Math.random() * 20)
socket.emit('message', 'Hello, your lucky number is ' + game.LuckyNumbers[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(() => {
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 | 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' })
})
|