websocket 前后端 写一个考试倒计时
时间: 2023-10-18 08:13:09 浏览: 248
考试倒计时
前端部分:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>考试倒计时</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var ws = new WebSocket("ws://localhost:8080");
ws.onmessage = function(event) {
$("#timer").text(event.data);
};
</script>
</head>
<body>
<h1>考试倒计时</h1>
<p id="timer"></p>
</body>
</html>
```
后端部分:
```javascript
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
let countDown = 60 * 60; // 60分钟
wss.on('connection', function connection(ws) {
ws.send(countDown + '秒');
const timer = setInterval(() => {
countDown--;
if (countDown > 0) {
ws.send(countDown + '秒');
} else {
clearInterval(timer);
ws.close();
}
}, 1000);
});
```
运行后,在浏览器中打开页面,即可看到倒计时效果。
阅读全文