deno.com

TCP 监听器: Ping

在 Github 上编辑

一个在 localhost 上 TCP 监听器的示例,如果写入消息,它将记录消息,如果连接到它,则关闭连接。

实例化 text decoder 的实例,以将 TCP 流字节读取回纯文本。
const decoder = new TextDecoder();
在 localhost 端口 8080 上实例化 TCP 监听器的实例。
const listener = Deno.listen({
  hostname: "127.0.0.1",
  port: 8080,
  transport: "tcp",
});
等待异步连接,这些连接已建立到我们的 TCP 监听器。
for await (const conn of listener) {
实例化缓冲区数组以存储我们读取的 TCP 流的内容。
  const buf = new Uint8Array(1024);
将 TCP 流的内容读取到我们的缓冲区数组中。
  await conn.read(buf);
这里我们记录读取到缓冲区数组中的字节结果。
  console.log("Server - received: ", decoder.decode(buf));
我们关闭已建立的连接。
  conn.close();
}

使用 Deno CLI 在本地运行 此示例

deno run --allow-net https://docs.deno.org.cn/examples/scripts/tcp_listener.ts

您找到您需要的了吗?

隐私政策