-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
70 lines (50 loc) · 1.57 KB
/
Copy pathserver.js
File metadata and controls
70 lines (50 loc) · 1.57 KB
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
const express = require('express'),
cors = require('cors'),
app = express(),
server = require("http").Server(app),
io = require("socket.io")(server, {
cors: {
origin: "*", // Allow all origins for simplicity, can be restricted later
methods: ["GET", "POST"]
}
});
usernames = [];
server.listen(process.env.PORT || 3001);
console.log("Server running...");
app.use(cors());
app.use(express.static('public'));
app.get("/", function (req, res) {
res.sendFile(__dirname + '/public/index.html');
});
io.sockets.on("connection", function (socket) {
console.log("Socket Connected...");
socket.on("new user", function (data, callback) {
if (usernames.indexOf(data) != -1) {
callback(false);
} else {
callback(true);
socket.username = data;
usernames.push(socket.username);
updateUsernames();
}
});
// Update Usernames
function updateUsernames(params) {
io.sockets.emit("usernames", usernames);
}
// Send Message
socket.on("send message", function (data) {
io.sockets.emit("new message", { msg: data.msg, user: socket.username, id: socket.id, count: data.count });
});
socket.on('typing', (data) => {
io.sockets.emit('typing', (socket.username));
});
// Disconnect
socket.on("disconnect", function (data) {
if (!socket.username) {
return;
}
usernames.splice(usernames.indexOf(socket.username), 1);
updateUsernames();
});
});