Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 33 additions & 12 deletions src/content/docs/sandbox/guides/websocket-connections.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ export default {
}

return new Response('Not found', { status: 404 });

}
};

Expand Down Expand Up @@ -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<Response> {
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');

Expand Down
Loading