-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
94 lines (83 loc) · 3.16 KB
/
index.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
var express = require("express");
var bodyParser = require("body-parser");
var session = require("express-session");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var http = require("http").createServer(app);
var io = require("socket.io")(http);
const userNameSet = new Set();
// parse application/json :接受 json 或者可以转换为json的数据格式
app.get("/", (req, res) => {
res.sendFile(__dirname + "/login.html");
});
app.get("/login", (req, res) => {
res.sendFile(__dirname + "/login.html");
});
app.get("/index", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/userName", (req, res) => {
const userName = req.body.userName || null;
if (userName === null) {
res.status(400);
res.send(false);
return;
}
if (userNameSet.has(userName)) {
res.status(403);
res.send("duplicate userName");
return;
}
res.cookie("userName", userName, {
// 设置该Cookie只可以由服务端访问,即前端JavaScript无法访问document.cookie获取该值,但控制台还是可以查看和修改
httpOnly: false,
// 只有通过HTTPS请求的Cookie才被使用,否则都认为是错误的Cookie
// secure: true,
// 设置保存Cookie的域名,浏览器查找Cookie时,子域名(如translate.google.com)可以访问主域名(google.com)下的Cookie,而主域名(google.com)不可以访问子域名(如translate.google.com)下的Cookie
// 本地测试可直接设置为localhost
domain: "localhost",
// 设置保存Cookie的路径,浏览器查找Cookie时,子路径(如/map)可以访问根路径('/')下设置的Cookie,而根路径('/')无法访问子路径(如/map)下设置的Cookie
path: "/",
// 通过expires设置Cookie过期时间为14天后
// expires: new Date(new Date().getTime() + 14 * 86400000),
// 通过maxAge设置Cookie过期时间为14天后
maxAge: 0.5 * 86400000,
});
res.send(true);
});
//在 index.html 引入 css 文件不成功,是因为没有设置 static 文件路径
app.use(express.static(__dirname));
io.use((socket, next) => {
let userName = socket.handshake.query.userName;
console.log("🚀 ~ file: index.js ~ line 62 ~ io.use ~ userName", userName);
next();
});
io.on("connection", (socket) => {
const connectUserName = socket.handshake.query.userName;
console.log(
"这里有新用户连接start:",
userNameSet,
userNameSet.has(connectUserName),
connectUserName
);
//如果没有这个 connectUserName
if (!userNameSet.has(connectUserName)) {
userNameSet.add(connectUserName);
console.log("这里有新用户连接:", connectUserName);
io.emit("connectUser", Array.from(userNameSet));
}
socket.on("disconnect", () => {
const disconUser = socket.handshake.query.userName;
userNameSet.delete(disconUser);
console.log("这里用户掉线了:", disconUser);
io.emit("disconUser", Array.from(userNameSet));
});
socket.on("newChatMessage", (msg) => {
console.log("message: " + msg);
io.emit("broadCastMessage", msg);
});
});
http.listen(3000, () => {
console.log("listening on *:3000");
});