forked from borjanebbal/webrtc-node-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
56 lines (47 loc) · 1.97 KB
/
server.js
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
const express = require('express')
const http = require('http')
const { Server } = require('socket.io')
const app = express()
const server = http.createServer(app)
const io = new Server(server)
app.use('/', express.static('public'))
io.on('connection', (socket) => {
socket.on('join', (roomId) => {
const selectedRoom = io.sockets.adapter.rooms.get(roomId)
const numberOfClients = selectedRoom ? selectedRoom.size : 0
if (numberOfClients === 0) {
console.log(`Creating room ${roomId} and emitting room_created socket event`)
socket.join(roomId)
socket.emit('room_created', roomId)
} else if (numberOfClients === 1) {
console.log(`Joining room ${roomId} and emitting room_joined socket event`)
socket.join(roomId)
socket.emit('room_joined', roomId)
} else {
console.log(`Can't join room ${roomId}, emitting full_room socket event`)
socket.emit('full_room', roomId)
}
})
// These events are emitted to all the sockets connected to the same room except the sender.
socket.on('start_call', (roomId) => {
console.log(`Broadcasting start_call event to peers in room ${roomId}`)
socket.to(roomId).emit('start_call')
})
socket.on('webrtc_offer', (event) => {
console.log(`Broadcasting webrtc_offer event to peers in room ${event.roomId}`)
socket.to(event.roomId).emit('webrtc_offer', event.sdp)
})
socket.on('webrtc_answer', (event) => {
console.log(`Broadcasting webrtc_answer event to peers in room ${event.roomId}`)
socket.to(event.roomId).emit('webrtc_answer', event.sdp)
})
socket.on('webrtc_ice_candidate', (event) => {
console.log(`Broadcasting webrtc_ice_candidate event to peers in room ${event.roomId}`)
socket.to(event.roomId).emit('webrtc_ice_candidate', event)
})
})
// START THE SERVER =================================================================
const port = process.env.PORT || 3000
server.listen(port, () => {
console.log(`Express server listening on port ${port}`)
})