-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
68 lines (59 loc) · 1.61 KB
/
app.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
const app = require("express")();
const http = require("http").createServer(app);
const io = require("socket.io")(http, {
cors: {
origin: "http://localhost:3000",
method: ["GET", "POST"],
},
});
// get
app.get("/", (req, res) => {
// sends html file as response
res.sendFile(__dirname + "/index.html");
});
io.on("connection", (socket) => {
let username = null;
// user connects
console.log("a user connected");
// broadcast userX is connected);
socket.on("user connection", (name) => {
console.log("emit login : ", name);
username = name;
io.emit("user log", {
type: "login",
name: name,
message: `welcome ${name} !`,
});
});
// user disconnects
socket.on("disconnect", () => {
console.log("user disconnected : ", username);
io.emit("user log", {
type: "logout",
name: username,
message: `${username} left the conversation...`,
});
});
// socket.on("user disconnect", (name) => {
// console.log("a user disconnected");
// console.log(name, " has logged out");
// io.emit("user log", {
// type: "logout",
// name: name,
// message: `${name} left the conversation...`,
// });
// });
// broadcast message
socket.on("chat message", ({ type, name, message }) => {
console.log(name + ": " + message);
io.emit("chat message", { type, name, message });
});
// broadcast user is typing
socket.on("isTyping", (name) => {
console.log(name, " is typing");
io.emit("user isTyping", name);
});
});
http.listen(4040, () => {
console.log("The application is running on localhost:4040!");
});