diff --git a/src/content/docs/sandbox/guides/websocket-connections.mdx b/src/content/docs/sandbox/guides/websocket-connections.mdx index 090152e2e33..2a9eaa2c271 100644 --- a/src/content/docs/sandbox/guides/websocket-connections.mdx +++ b/src/content/docs/sandbox/guides/websocket-connections.mdx @@ -129,6 +129,7 @@ export default { } return new Response('Not found', { status: 404 }); + } }; @@ -158,23 +159,43 @@ import { getSandbox } from '@cloudflare/sandbox'; export { Sandbox } from '@cloudflare/sandbox'; +let initialized = false; + export default { async fetch(request: Request, env: Env): Promise { - const sandbox = getSandbox(env.Sandbox, 'data-processor'); - // Incoming HTTP request needs real-time data from sandbox - const wsRequest = new Request('ws://internal', { - headers: { - 'Upgrade': 'websocket', - 'Connection': 'Upgrade' - } - }); + // Get or create a sandbox instance + const sandbox = getSandbox(env.Sandbox, 'data-processor'); - // Connect to WebSocket service in sandbox - const wsResponse = await sandbox.wsConnect(wsRequest, 8080); - // Process WebSocket stream and return HTTP response - // (Implementation depends on your needs) + // Check for WebSocket upgrade + const upgrade = request.headers.get('Upgrade')?.toLowerCase(); + + if (upgrade === 'websocket') { + // Initialize server on first connection + if (!initialized) { + await sandbox.writeFile( + '/workspace/server.js', + `Bun.serve({ + port: 8080, + fetch(req, server) { + server.upgrade(req); + }, + websocket: { + message(ws, msg) { + ws.send(\`Echo: \${msg}\`); + } + } + });` + ); + await sandbox.startProcess( + 'bun /workspace/server.js' + ); + initialized = true; + } + // Connect to WebSocket server + return await sandbox.wsConnect(request, 8080); + } return new Response('Processed real-time data');