diff options
author | 2022-10-19 02:36:22 -0700 | |
---|---|---|
committer | 2022-10-19 02:36:22 -0700 | |
commit | ff36fa8a53801a39973419fd7b20c17d34ce8087 (patch) | |
tree | 4b30782aeec118379a49d8c761d98898c9ad41fa /examples | |
parent | 19682b4225d3f18fd9bc318f264ab36d661c5487 (diff) | |
download | bun-ff36fa8a53801a39973419fd7b20c17d34ce8087.tar.gz bun-ff36fa8a53801a39973419fd7b20c17d34ce8087.tar.zst bun-ff36fa8a53801a39973419fd7b20c17d34ce8087.zip |
Add websocket hot example
Diffstat (limited to 'examples')
-rw-r--r-- | examples/bun-hot-websockets.js | 89 |
1 files changed, 89 insertions, 0 deletions
diff --git a/examples/bun-hot-websockets.js b/examples/bun-hot-websockets.js new file mode 100644 index 000000000..1656d2eb5 --- /dev/null +++ b/examples/bun-hot-websockets.js @@ -0,0 +1,89 @@ +// To run this example: +// +// bun --hot bun-hot-websockets.js +// + +const css = ([inner]) => { + return inner; +}; + +const styles = css` + #bun { + margin: 0 auto; + margin-top: 200px; + object-fit: cover; + } + html, + body { + margin: 0; + padding: 0; + } + body { + background: #f1239f; + font-family: "Inter", sans-serif; + display: flex; + align-items: center; + justify-content: center; + align-content: center; + color: white; + } + h1 { + padding: 0; + text-align: center; + font-size: 3rem; + -webkit-text-stroke: 2px black; + } + * { + box-sizing: border-box; + } +`; + +export default { + websocket: { + message(ws, msg) { + ws.send(styles); + }, + }, + fetch(req, server) { + if (req.url.endsWith("/hot")) { + if (server.upgrade(req)) + return new Response("", { + status: 101, + }); + } + + return new Response( + ` + <!DOCTYPE html> + <html> + <head> + <meta charset="utf-8"> + <title>WebSockets</title> + </head> + <body> + <style></style> + <script> + const ws = new WebSocket("ws://localhost:3000/hot"); + const style = document.querySelector("style"); + ws.onmessage = (e) => { + style.innerHTML = e.data; + }; + setInterval(() => { + ws.send("ping"); + }, 8); + </script> + <div id="app"> + <img src="https://bun.sh/logo.svg" alt="Bun" id='bun' /> + <h1>bun --hot websockets</h1> + </div> + </body> + + `, + { + headers: { + "Content-Type": "text/html; charset=utf-8", + }, + } + ); + }, +}; |