forked from quanhv94/talk-to-stranger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
73 lines (62 loc) · 2.12 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const express = require('express')
const app = express()
const cors = require('cors')
const port = process.env.PORT || 8888
const http = require('http').createServer(app)
const io = require('socket.io')(http)
const uuidv1 = require('uuid/v1')
const path = require('path')
app.use(cors())
let watingSockets = [];
io.on('connection', (socket) => {
console.log('connected')
socket.emit('connected', { socketId: socket.id })
socket.on('start-chat', (config) => {
socket.config = config;
let availableSockets = watingSockets.filter((watingSocket) => (
socket.id !== watingSocket.id &&
(socket.config.partnerGender === 0 || watingSocket.config.yourGender === socket.config.partnerGender) &&
(watingSocket.config.partnerGender === 0 || socket.config.yourGender === watingSocket.config.partnerGender)
))
let partner = availableSockets[0]
if (partner) {
let roomId = uuidv1()
socket.join(roomId, () => {
partner.join(roomId, () => {
socket.roomId = roomId
partner.roomId = roomId
watingSockets = watingSockets.filter(x => x.id != partner.id)
io.to(roomId).emit('pair-success')
})
})
} else {
watingSockets.push(socket)
}
})
socket.on('message', (message) => {
io.to(socket.roomId).emit('receive-message', { socketId: socket.id, content: message })
})
socket.on('leave-chat', () => {
socket.leave(socket.roomId)
io.to(socket.roomId).emit('partner-leave-chat');
})
socket.on('start-typing', () => {
socket.broadcast.to(socket.roomId).emit('partner-start-typing');
})
socket.on('stop-typing', () => {
socket.broadcast.to(socket.roomId).emit('partner-stop-typing');
})
socket.on('disconnect', () => {
console.log('disconnect')
watingSockets = watingSockets.filter(x => x.id != socket.id)
socket.leave(socket.roomId)
io.to(socket.roomId).emit('partner-leave-chat');
});
});
app.use(express.static(path.resolve(__dirname, './build')))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, './build/index.js'))
})
http.listen(port, () => {
console.log('App is running')
});