Server Socket Emit
Video Lecture
Description
When a new socket object is created from a connection server side, we can use that socket anytime, to send a message to the connected client.
./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 | 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.on('disconnect', () => {
console.log('socket disconnected : ' + socket.id)
})
})
server.listen(port, () => {
console.log('Server listening on port ' + port)
})
|
./src/client/client.ts
| 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>'
})
|