Browse Source

basic

master
zhangjiming 5 months ago
parent
commit
6d368fcf12
  1. 2
      package-lock.json
  2. 2
      package.json
  3. 22
      public/index.html
  4. 2
      public/lib/zepto.min.js
  5. 31
      public/main.js
  6. 6
      public/style.css
  7. 26
      public/test.html
  8. 53
      src/index.ts

2
package-lock.json

@ -9,10 +9,12 @@
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"body-parser": "^2.1.0",
"express": "^5.0.1",
"ws": "^8.18.1"
},
"devDependencies": {
"@types/body-parser": "^1.19.5",
"@types/express": "^5.0.0",
"@types/node": "^22.13.4",
"@types/ws": "^8.5.14",

2
package.json

@ -14,10 +14,12 @@
"license": "ISC",
"description": "",
"dependencies": {
"body-parser": "^2.1.0",
"express": "^5.0.1",
"ws": "^8.18.1"
},
"devDependencies": {
"@types/body-parser": "^1.19.5",
"@types/express": "^5.0.0",
"@types/node": "^22.13.4",
"@types/ws": "^8.5.14",

22
public/index.html

@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="main">
<div class="form">
<label for="username">用户名</label>
<input type="text" id="username" />
<label for="password">密码</label>
<input type="password" id="password" />
<button type="submit" id="submit_user_pwd">确定</button>
</div>
</div>
<script src="lib/zepto.min.js"></script>
<script src="main.js"></script>
</body>
</html>

2
public/lib/zepto.min.js
File diff suppressed because it is too large
View File

31
public/main.js

@ -0,0 +1,31 @@
const ws = new WebSocket(`ws://${window.location.host}`);
ws.onopen = () => {
console.log("Connected to server");
ws.send("Hello from client!");
};
ws.onmessage = event => {
console.log(`Message from server: ${event.data}`);
};
ws.onclose = () => {
console.log("Disconnected from server");
};
$("#submit_user_pwd").on("click", () => {
const name = $("#username").val();
const pwd = $("#password").val();
$.ajax({
type: "POST",
url: "/test",
data: JSON.stringify({ name, pwd }),
contentType: "application/json",
success: res => {
console.log("Success", res);
},
error: err => {
console.error("Error", err);
},
});
});

6
public/style.css

@ -0,0 +1,6 @@
.form {
display: flex;
flex-direction: column;
align-items: start;
gap: 8px;
}

26
public/test.html

@ -1,26 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
const ws = new WebSocket("ws://localhost:3003");
ws.onopen = () => {
console.log("Connected to server");
ws.send("Hello from client!");
};
ws.onmessage = event => {
console.log(`Message from server: ${event.data}`);
};
ws.onclose = () => {
console.log("Disconnected from server");
};
</script>
</body>
</html>

53
src/index.ts

@ -1,38 +1,51 @@
import express from "express";
import { Server } from "ws";
import http from 'http';
import http from "http";
import bodyParser from "body-parser";
const app = express();
app.use(express.static('public'));
app.use(express.static("public"));
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.post("/test", (req, res) => {
(req.app.locals["wss"] as Server).clients.forEach(client => {
if (client.readyState === 1) {
client.send(JSON.stringify(req.body));
}
});
res.json({ success: true, data: req.body });
});
const server = http.createServer(app);
// 在HTTP服务器上初始化WebSocket服务器
const wss = new Server({server});
wss.on('connection',(ws) => {
console.log('Client connected');
ws.send('Welcome to the WebSocket server!');
ws.on('message', (message) => {
console.log(`Received message: ${message}`);
const wss = new Server({ server });
// 广播收到的消息给所有连接的客户端
wss.clients.forEach(client => {
if (client.readyState === ws.OPEN) {
client.send(message.toString());
}
});
})
wss.on("connection", ws => {
console.log("Client connected");
ws.send("Welcome to the WebSocket server!");
ws.on("message", message => {
console.log(`Received message: ${message}`);
// 广播收到的消息给所有连接的客户端
wss.clients.forEach(client => {
if (client.readyState === ws.OPEN) {
client.send(message.toString());
}
});
});
// 当连接关闭时触发
ws.on('close', () => {
console.log('Client disconnected');
});
})
ws.on("close", () => {
console.log("Client disconnected");
});
});
app.locals["wss"] = wss;
// 监听端口
const PORT = process.env.PORT || 3003;
server.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
console.log(`Server is listening on port ${PORT}`);
});
Loading…
Cancel
Save