/
index.ts
62 lines (50 loc) · 1.6 KB
/
index.ts
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
import * as express from "express";
import { createServer } from "http";
import { Server } from "socket.io";
import * as morgan from "morgan";
const app = express();
const server = createServer(app);
const io = new Server(server, { serveClient: false });
// via https://fly.io/blog/always-be-connecting-with-https/
app.use(function (req, res, next) {
if (req.get("X-Forwarded-Proto") == "http") {
// request was via http, so redirect to https
res.redirect("https://" + req.headers.host + req.url);
} else {
next();
}
});
app.use(
morgan("combined", {
skip: (req, res) => !(req.path === "/") && !req.path.includes(".html"), // Only log requests to "/" & to `.html` routes
})
);
app.use(express.static("public"));
const livetexts = new Map<string, string>();
const dynamicNsp = io.of(/^\/\w+(-\w+)*$/).on("connection", (socket) => {
const newNamespace = socket.nsp;
socket.emit("notice", { name: newNamespace.name });
if (livetexts.has(newNamespace.name)) {
socket.emit("text", livetexts.get(newNamespace.name));
}
newNamespace.emit("notice", {
size: newNamespace.sockets.size,
});
socket.on("text", (text) => {
livetexts.set(newNamespace.name, text);
// Emit text to all clients except sender
socket.broadcast.emit("text", text);
});
socket.on("disconnect", () => {
if (newNamespace.sockets.size === 0) {
livetexts.delete(newNamespace.name);
}
newNamespace.emit("notice", {
size: newNamespace.sockets.size,
});
});
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`server started on http://localhost:${PORT}`);
});