Skip to content

Commit

Permalink
feat: server push demo
Browse files Browse the repository at this point in the history
  • Loading branch information
stevenleep committed Jul 19, 2022
1 parent 8db7c07 commit 2346eb5
Show file tree
Hide file tree
Showing 5 changed files with 433 additions and 0 deletions.
40 changes: 40 additions & 0 deletions extensions/server-push/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const http = require("http");
const {
setEventStreamHeaders,
sendEvent,
reuseServerPushChanel,
} = require("./eventstream");
const url = require("url");

global.serverPushChanel = null;
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url);
const { pathname, query } = parsedUrl;

res.setHeader("access-control-allow-origin", "*");

if (pathname === "/") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>Hello World</h1>");
}

if (pathname === "/evt") {
setEventStreamHeaders(res);
global.serverPushChanel = res;
sendEvent(req, res);
}

// client message
if (pathname === "/msg") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(new Date().toString());

if (global.serverPushChanel) {
reuseServerPushChanel(global.serverPushChanel, query, res);
}
}
});

server.listen(8900, "localhost", () => {
console.log("Server is running on port 8900");
});
29 changes: 29 additions & 0 deletions extensions/server-push/eventstream.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
exports.setEventStreamHeaders = function (res) {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", true);
};

exports.sendEvent = function (req, res) {
setInterval(() => {
res.write(
`data: ${JSON.stringify({
type: "event",
mode: "ping",
message: "server push, ping",
})} \n\n`
);
}, 3000);
};

exports.reuseServerPushChanel = function (serverPushChanel, query, res) {
serverPushChanel.write(
`data: ${JSON.stringify({
type: "event",
mode: "msg",
message: query,
})} \n\n`
);
};
54 changes: 54 additions & 0 deletions extensions/server-push/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Client</title>
</head>
<body>
<h2>发送消息</h2>
<label for="m">
<input type="text" id="m" />
</label>
<button type="button" id="sendBtn">发送</button>

<h2>接受消息</h2>
<h4 class="connect-status">Pending connection...</h4>
<ul class="message-container"></ul>
</body>

<script>
const eventSource = new EventSource("http://localhost:8900/evt");
eventSource.onopen = (event) => {
document.querySelector(".connect-status").innerHTML =
"Connected to server";
};
eventSource.onmessage = (event) => {
const message = JSON.parse(event.data);
const messageNode = document.createElement("li");
if (message.mode === "msg") {
messageNode.setAttribute("style", "color: red");
}
messageNode.innerHTML = `<strong>${
message?.mode
}</strong>: ${decodeURIComponent(message.message)}`;
document.querySelector(".message-container").appendChild(messageNode);
};

sendMessage();

function sendMessage() {
const messageInput = document.querySelector("#m");
const sendBtn = document.querySelector("#sendBtn");

sendBtn.addEventListener("click", () => {
fetch(
"http://localhost:8900/msg" + "?message=" + messageInput.value
).then((response) => {
console.log(response);
});
});
}
</script>
</html>
15 changes: 15 additions & 0 deletions extensions/server-push/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "server-push",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon app.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"nodemon": "^2.0.19"
}
}
Loading

0 comments on commit 2346eb5

Please sign in to comment.