-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
53 lines (44 loc) · 1.18 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
const app = require("express")();
const server = require("http").createServer(app);
const cors = require("cors")
// noinspection JSValidateTypes
const io = require('socket.io')(server, {
cors: {
origin: "http://localhost:8080",
methods: ["GET", "POST"]
}
});
let users = [];
let messages = [];
let index = 0;
io.on("connection", socket => {
socket.emit("loggedIn", {
users: users.map(s => s.username),
messages,
})
socket.on("newUser", username => {
console.log(`${username} has arrived at the party`)
socket.username = username;
users.push(socket)
io.emit("userOnline", socket.username)
});
socket.on("msg", msg => {
let message = {
index,
username: socket.username,
msg
}
messages.push(message)
io.emit("msg", message)
index++;
})
//disconnect
socket.on("disconnect", () => {
console.log(`${socket.username} has left the party.`);
io.emit("userLeft", socket.username);
users.splice(users.indexOf(socket), 1);
})
})
server.listen(3000, () => {
console.log("listening on port 3000")
})