-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathserver.js
51 lines (43 loc) · 1.09 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
const http = require('http')
const express = require('express')
const app = express()
const socketio = require('socket.io')
const server = http.createServer(app)
const io = socketio(server)
let users = {
arnav: 'agag123',
}
let socketMap = {}
io.on('connection', (socket) => {
console.log('connected with socket id =', socket.id)
function login(s, u) {
s.join(u)
s.emit('logged_in')
socketMap[s.id] = u
console.log(socketMap)
}
socket.on('login', (data) => {
if (users[data.username]) {
if (users[data.username] == data.password) {
login(socket, data.username)
} else {
socket.emit('login_failed')
}
} else {
users[data.username] = data.password
login(socket, data.username)
}
})
socket.on('msg_send', (data) => {
data.from = socketMap[socket.id]
if (data.to) {
io.to(data.to).emit('msg_rcvd', data)
} else {
socket.broadcast.emit('msg_rcvd', data)
}
})
})
app.use('/', express.static(__dirname + '/public'))
server.listen(3344, () => {
console.log('Started on http://localhost:3344')
})