這個(gè)示例是一個(gè) TCP echo 服務(wù),接收 8080 端口的連接,把接收到的任何數(shù)據(jù)返回給客戶端。
const hostname = "0.0.0.0";
const port = 8080;
const listener = Deno.listen({ hostname, port });
console.log(`Listening on ${hostname}:${port}`);
for await (const conn of listener) {
Deno.copy(conn, conn);
}
當(dāng)這個(gè)程序啟動(dòng)時(shí),它會(huì)拋出一個(gè)沒有網(wǎng)絡(luò)權(quán)限的錯(cuò)誤。
$ deno run https://deno.land/std/examples/echo_server.ts
error: Uncaught PermissionDenied: network access to "0.0.0.0:8080", run again with the --allow-net flag
? $deno$/dispatch_json.ts:40:11
at DenoError ($deno$/errors.ts:20:5)
...
為了安全,Deno 不允許程序訪問網(wǎng)絡(luò),除非顯式賦予權(quán)限。使用一個(gè)命令行選項(xiàng)來允許程序訪問網(wǎng)絡(luò):
deno run --allow-net https://deno.land/std/examples/echo_server.ts
嘗試用 netcat 向它發(fā)送數(shù)據(jù)。
$ nc localhost 8080
hello world
hello world
像示例 cat.ts 一樣,copy() 函數(shù)不會(huì)產(chǎn)生不必要的內(nèi)存拷貝。它從內(nèi)核接收數(shù)據(jù)包,然后發(fā)送回去,就這么簡單。
更多建議: