Export a connect() handler to let a Worker accept an inbound TCP connection and read and write raw bytes on it. The handler receives a Socket object, the same type returned by connect() from cloudflare:sockets for outbound connections.
A Worker receives a connection in its connect() handler when another Worker forwards a TCP connection to it over a service binding, by calling connect() on the binding:
// Worker A forwards a TCP connection to Worker B over a service binding
export default {
async fetch(request, env) {
const socket = env.BACKEND.connect("example.com:1234");
// Read from and write to socket.readable / socket.writable
return new Response(socket.readable);
},
};export default {
async connect(socket, env, ctx) {
const writer = socket.writable.getWriter();
await writer.write(new TextEncoder().encode("hello"));
await writer.close();
},
};interface Env {}
export default {
async connect(socket: Socket, env: Env, ctx: ExecutionContext) {
const writer = socket.writable.getWriter();
await writer.write(new TextEncoder().encode("hello"));
await writer.close();
},
} satisfies ExportedHandler<Env>;You can also implement connect() as a method on a WorkerEntrypoint class, which lets a single Worker expose a connect() handler alongside other RPC methods:
import { WorkerEntrypoint } from "cloudflare:workers";
export class Backend extends WorkerEntrypoint {
async connect(socket) {
const writer = socket.writable.getWriter();
await writer.write(new TextEncoder().encode("hello"));
await writer.close();
}
}socketSocket- The inbound
Socketused to read and write raw bytes on the connection. socket.openedresolves with aSocketInfoobject. On aconnect()handler,localAddressis set to the address the caller passed toconnect()on the service binding.
- The inbound
envobject- The bindings available to the Worker.
ctxobject- The context associated with the Worker, containing
waitUntil()andpassThroughOnException().
- The context associated with the Worker, containing
A Worker that does not export a connect() handler rejects any connection forwarded to it.
- TCP sockets — Create outbound TCP connections and work with the
SocketAPI. - Service bindings — Call one Worker from another, including forwarding TCP connections with
connect().