Skip to content

Commit

Permalink
WebSocket Sample
Browse files Browse the repository at this point in the history
  • Loading branch information
yoshikouki committed Mar 2, 2024
1 parent 7eae80d commit 080afd0
Show file tree
Hide file tree
Showing 8 changed files with 343 additions and 0 deletions.
175 changes: 175 additions & 0 deletions sample/with-websocket/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore

# Logs

logs
_.log
npm-debug.log_
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Caches

.cache

# Diagnostic reports (https://nodejs.org/api/report.html)

report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json

# Runtime data

pids
_.pid
_.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover

lib-cov

# Coverage directory used by tools like istanbul

coverage
*.lcov

# nyc test coverage

.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)

.grunt

# Bower dependency directory (https://bower.io/)

bower_components

# node-waf configuration

.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)

build/Release

# Dependency directories

node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)

web_modules/

# TypeScript cache

*.tsbuildinfo

# Optional npm cache directory

.npm

# Optional eslint cache

.eslintcache

# Optional stylelint cache

.stylelintcache

# Microbundle cache

.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history

.node_repl_history

# Output of 'npm pack'

*.tgz

# Yarn Integrity file

.yarn-integrity

# dotenv environment variable files

.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)

.parcel-cache

# Next.js build output

.next
out

# Nuxt.js build / generate output

.nuxt
dist

# Gatsby files

# Comment in the public line in if your project uses Gatsby and not Next.js

# https://nextjs.org/blog/next-9-1#public-directory-support

# public

# vuepress build output

.vuepress/dist

# vuepress v2.x temp and cache directory

.temp

# Docusaurus cache and generated files

.docusaurus

# Serverless directories

.serverless/

# FuseBox cache

.fusebox/

# DynamoDB Local files

.dynamodb/

# TernJS port file

.tern-port

# Stores VSCode versions used for testing VSCode extensions

.vscode-test

# yarn v2

.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

# IntelliJ based IDEs
.idea

# Finder (MacOS) folder config
.DS_Store
13 changes: 13 additions & 0 deletions sample/with-websocket/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# basic-hot-reload

## Setup

```bash
bun install
```

# To run

```bash
bun dev
```
Binary file added sample/with-websocket/bun.lockb
Binary file not shown.
20 changes: 20 additions & 0 deletions sample/with-websocket/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "basic-hot-reload",
"module": "src/index.ts",
"type": "module",
"scripts": {
"dev": "bun --hot src/index.tsx"
},
"devDependencies": {
"@types/bun": "latest",
"@types/react": "^18.2.61",
"@types/react-dom": "^18.2.19",
"add": "^2.0.6",
"bun": "^1.0.29",
"typescript": "^5"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}
15 changes: 15 additions & 0 deletions sample/with-websocket/src/app.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export const App = () => {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Bun Hot Reload</title>
<script src="/dist/client.js" defer />
</head>
<body>
<div id="root" />
</body>
</html>
);
};
36 changes: 36 additions & 0 deletions sample/with-websocket/src/client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";

const ws = new WebSocket("ws://localhost:3000");

const Client = () => {
const [tick, setTick] = useState("");

useEffect(() => {
ws.onopen = () => {
console.log("connected");
};
ws.onmessage = (event) => {
setTick(event.data.toString());
};
ws.onclose = () => {
console.log("disconnected");
};
ws.onerror = (error) => {
console.error(error);
};
});

return (
<>
<div>{tick}</div>
<button onClick={() => ws.send(new Date().toISOString())} type="button">
Push
</button>
</>
);
};

const domNode = document.getElementById("root") ?? undefined;
const root = createRoot(domNode);
root.render(<Client />);
49 changes: 49 additions & 0 deletions sample/with-websocket/src/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import configureHotReload from "bun-hot-reload";
import { renderToString } from "react-dom/server";
import { App } from "./app";

Bun.serve(
configureHotReload(
{
fetch: async (req, server) => {
const url = new URL(req.url);
if (url.pathname === "/") {
if (server.upgrade(req)) {
return;
}
return new Response(renderToString(<App />), {
headers: { "Content-Type": "text/html" },
});
}
if (url.pathname === "/dist/client.js") {
return new Response(Bun.file("dist/client.js"), {
headers: { "Content-Type": "application/javascript" },
});
}
return new Response("Not Found", { status: 404 });
},

websocket: {
message(ws, message) {
console.log("WebSocket message:", message);
ws.send(new Date().toISOString());
},
open(ws) {
console.log("WebSocket connected");
setInterval(() => {
ws.send(new Date().toISOString());
}, 1000);
},
close(ws, code, message) {
console.log("WebSocket disconnected");
},
},
},
{
buildConfig: {
entrypoints: ["src/client.tsx"],
outdir: "dist",
},
},
),
);
35 changes: 35 additions & 0 deletions sample/with-websocket/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"compilerOptions": {
// Enable latest features
"lib": ["ESNext"],
"target": "ESNext",
"module": "ESNext",
"moduleDetection": "force",
"jsx": "react-jsx",
"allowJs": true,

// Bundler mode
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,

// Best practices
"strict": true,
"skipLibCheck": true,
"noFallthroughCasesInSwitch": true,

// Some stricter flags (disabled by default)
"noUnusedLocals": false,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false,

// Paths
"baseUrl": "../../",
"paths": {
"bun-hot-reload": [
"./src/index.ts"
],
}
}
}

0 comments on commit 080afd0

Please sign in to comment.