-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (65 loc) · 2.37 KB
/
index.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
const app = require('express')();
const http = require('http').Server(app);
const path = require("path")
const io = require('socket.io')(http);
const fs = require('fs');
let usersRawdata = fs.readFileSync('./data/users.json');
let roomsRawdata = fs.readFileSync('./data/rooms.json');
let chatDataRawdata = fs.readFileSync('./data/chatData.json');
let users = JSON.parse(usersRawdata);
let rooms = JSON.parse(roomsRawdata);
let chatData = JSON.parse(chatDataRawdata);
console.log(users)
app.get("/", (req,res) => {
res.sendFile(path.join(__dirname,'index.html'));
})
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('login', (data) => {
console.log(data)
let user = users.find(user => user.username === data.username)
if (user === undefined) {
socket.emit("loginstate", "Tài khoản không tồn tại");console.log("Login not successful")
} else {
if(user.password === data.password) {
console.log("Login successful");
socket.emit('loginstate',true)
let chat = chatData.find(chat => chat.roomcode === user.roomcode);
let roomList = users.find(user => user.roomcode === chat.roomcode)
socket.emit('getMessage',{
data : chat,
list: roomList
})
socket.on('message',(msg)=>{
chat.data.push({
sender: user.username,
message: msg,
})
console.log(chat)
socket.emit('getMessage',chat)
})
socket.on('update', ()=>{
socket.emit('getMessage',chat)
})
} else {
socket.emit("loginstate", "Tên đăng nhập hoặc mật khẩu không đúng");
console.log("Login not successful")
}
}
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
setInterval(()=>{
let chatDataData = JSON.stringify(chatData);
let roomsData = JSON.stringify(rooms);
let usersData = JSON.stringify(users);
fs.writeFileSync('./data/chatData.json', chatDataData);
fs.writeFileSync('./data/rooms.json', roomsData);
fs.writeFileSync('./data/users.json', usersData);
console.log("Data saved!")
},10000)
http.listen(80, () => {
console.log('listening on *:80');
});