summaryrefslogtreecommitdiff
path: root/Year_3/Web/chat-socket-io/index.js
blob: b59cb72e4e87af4c742e631e72e532889d7669f1 (plain)
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
const express = require("express");
const http = require("http");
const { Server } = require("socket.io");

const app = express();

app.set("view engine", "pug");

const server = http.createServer(app);
const io = new Server(server);

app.get("/", (req, res) => {
    res.render("index");
});

app.use(express.static("assets"));

app.get("*", (req, res) => {
    res.render("404");
});

const users = {};

io.on("connection", (socket) => {
    console.log("A user is connected: " + socket.id);
    io.to(socket.id).emit("set user", socket.id);
    users[socket.id] = socket.id;

    socket.on("disconnect", () => {
        console.log("A user is disconnected");
    });

    socket.on("chat message", (message) => {
        socket.broadcast.emit("chat message", message);
    });

    socket.on("handle error", (msg) => {
        io.emit("handle error", msg);
    });

    socket.on("set user", (username) => {
        users[socket.id] = username;
        io.to(socket.id).emit("set user", username);
    });
});

server.listen(3000, () => {
    console.log("Listening on port 3000");
});