-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
73 lines (54 loc) · 1.52 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
const app = require("./backend/app");
const debug = require("debug")("node-angular");
const http = require("http");
const dotenv=require('dotenv')
// const {Server}=require('socket.io')
// app.use(dotenv)
// const socketIO =require('socket.io')
const server = http.createServer(app);
const io = require('socket.io')(server, {
cors: {
origin: '*'
}
});
//socketio
function addUser(userName, id) {
if (!userList.has(userName)) {
userList.set(userName, new Set(id));
console.log(userList)
} else {
userList.get(userName).add(id);
}
}
function removeUser(userName, id) {
if (userList.has(userName)) {
let userIds = userList.get(userName);
if (userIds.size == 0) {
userList.delete(userName);
}
}
}
app.get('/', (req, res) => {
res.send('Heello world');
})
let userList = new Map();
io.on('connection', (socket) => {
let userName = socket.handshake.query.userName;
console.log('user connected : ',userName)
addUser(userName, socket.id);
socket.broadcast.emit('user-list', [...userList.keys()]);
socket.emit('user-list', [...userList.keys()]);
socket.on('message', (msg) => {
socket.broadcast.emit('message-broadcast', {message: msg, userName: userName});
console.log(msg)
})
socket.on('disconnect', (reason) => {
removeUser(userName, socket.id);
})
});
//rest
const port = ( "3000");
app.set("port", port);
server.listen(port,()=>{
console.log('Server running at port : ',port)
});