node:net ↗ を使い、net.Socket ↗ でサーバーへ TCP ソケットによる直接接続を作成できます。
これらの関数は、組み込みの cloudflare:sockets モジュールの connect 機能を使います。
import net from "node:net";
const exampleIP = "127.0.0.1";
export default {
async fetch(req) {
const socket = new net.Socket();
socket.connect(4000, exampleIP, function () {
console.log("Connected");
});
socket.write("Hello, Server!");
socket.end();
return new Response("Wrote to server", { status: 200 });
},
};import net from "node:net";
const exampleIP = "127.0.0.1";
export default {
async fetch(req): Promise<Response> {
const socket = new net.Socket();
socket.connect(4000, exampleIP, function () {
console.log("Connected");
});
socket.write("Hello, Server!");
socket.end();
return new Response("Wrote to server", { status: 200 });
},
} satisfies ExportedHandler;加えて、net.BlockList ↗ や net.SocketAddress ↗ などのほかの API も使えます。
net.Server ↗ クラスは、Workers ではサポートされない点に注意してください。
node:net の API 全体は、Node.js の node:net ドキュメント ↗ に記載されています。