0
点赞
收藏
分享

微信扫一扫

16.WEB渗透测试--Kali Linux(四)

whiteMu 03-16 09:00 阅读 4

9a69fede8b2044a79dd834e3e48f20b4.png前期回顾   

避免阻塞主线程 —— Web Worker 示例项目-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/m0_57904695/article/details/136721297?spm=1001.2014.3001.5501

目录

@CSDN 彩色之外

📝 前言

🛠️ 安装

✂️ 运行服务器

✂️ 运行index.html

♻️ 贡献


仓库点我👉及时推送到客户端消息

@CSDN 彩色之外

📝 前言

 服务器每秒像客户端发送一次服务端生成的时间

 index.html

<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <title>EventSource 示例</title>
</head>

<body>
    <h2>服务器发送的消息:</h2>
    <ul id="messages"></ul>

    <script>
        // 创建一个指向你的服务器端点的 EventSource 实例
        var eventSource = new EventSource('http://localhost:3000/events');

        // 使用 onmessage 事件监听器来接收消息
        eventSource.onmessage = function (event) {
            // 获取消息列表的元素
            var messagesElement = document.getElementById('messages');

            // 创建一个新的列表项元素,并设置其内容为接收到的消息
            var messageElement = document.createElement('li');
            messageElement.textContent = event.data;

            // 将新的列表项添加到消息列表中
            messagesElement.appendChild(messageElement);
        };

        // 监听错误事件
        eventSource.onerror = function (error) {
            console.error('EventSource failed:', error);
            // 在出现错误时关闭 EventSource
            eventSource.close();
        };
    </script>
</body>

</html>

server.js 

const express = require("express");
const cors = require("cors");
const app = express();
const PORT = 3000;

// 设置根URL的GET路由
app.get("/", (req, res) => {
	res.send(
		`<b>Hello, World!</b> - <br>使用 VS Code 的 Five Server<br> 1. 在 VS Code 中安装 Five Server 扩展。<br> 2. 与 Live Server 类似,重启 VS Code,打开你的项目文件夹。<br> 3. 找到你的 HTML 文件,右键点击并选择“Open with Five Server”。`
	);
});

// 允许跨域请求
app.use(cors());

app.get("/events", (req, res) => {
	res.setHeader("Content-Type", "text/event-stream");
	res.setHeader("Cache-Control", "no-cache");
	res.setHeader("Connection", "keep-alive");

	// 发送消息到客户端
	const sendMessage = () => {
		const data = `服务器时间: ${new Date()}`;
		res.write(`data: ${data}\n\n`);

		// 每秒发送一次
		setTimeout(sendMessage, 1000);
	};

	sendMessage();
});

app.listen(PORT, () => {
	console.log(`服务器运行在 http://localhost:${PORT}`);
});

🛠️ 安装

npm install express cors

✂️ 运行服务器

node server.js

 ✂️ 运行index.html

使用 VS Code 的 Five Server

1. 在 VS Code 中安装 Five Server 扩展。

2. 与 Live Server 类似,重启 VS Code,打开你的项目文件夹。

3. 找到你的 HTML 文件,右键点击并选择“Open with Five Server”。

 

 功能描述

   > 服务器 (server.js): 设置一个 SSE 端点 /events,每秒向客户端发送当前时间。

   > 客户端 (index.html): 使用 EventSource 接口连接到 SSE 端点,并在页面上显示接收到的消息。

   技术栈

   > Node.js: 服务器环境。

   > Express: Node.js 的 web 应用框架,用于设置 SSE 端点。

   > CORS: 用于解决跨域请求的问题。

   > HTML/JavaScript: 客户端页面和逻辑。

♻️ 贡献

如果你有任何改进的建议或想要贡献代码,请随时创建 pull 请求或提交问题。

 

举报

相关推荐

0 条评论