Skip to content

非公式 / UnofficialCloudflare, Inc. 非提携。アカウント情報は入力しないでください。Not affiliated with Cloudflare, Inc. Do not enter Cloudflare credentials here.Official docsこのサイトについてプライバシー

net

最終更新 Markdown で表示Agent セットアップ

node:net ↗ を使い、net.Socket ↗ でサーバーへ TCP ソケットによる直接接続を作成できます。

これらの関数は、組み込みの cloudflare:sockets モジュールの connect 機能を使います。

index.jsjs
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 });
	},
};
index.tsts
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 ドキュメント ↗ に記載されています。

役に立ちましたか?