TCP 套接字和 TLS
Deno 部署支援傳出的 TCP 和 TLS 連線。這些 API 讓您可以使用資料庫,例如 PostgreSQL、SQLite、MongoDB 等,搭配部署。
Deno.connect
建立外連 TCP 連線。
函式定義與 Deno 相同,限制為 transport
選項只能為 tcp
,且 hostname
不能為 localhost 或空值。
function Deno.connect(options: ConnectOptions): Promise<Conn>
範例
async function handler(_req) {
// Make a TCP connection to example.com
const connection = await Deno.connect({
port: 80,
hostname: "example.com",
});
// Send raw HTTP GET request.
const request = new TextEncoder().encode(
"GET / HTTP/1.1\nHost: example.com\r\n\r\n",
);
const _bytesWritten = await connection.write(request);
// Read 15 bytes from the connection.
const buffer = new Uint8Array(15);
await connection.read(buffer);
connection.close();
// Return the bytes as plain text.
return new Response(buffer, {
headers: {
"content-type": "text/plain;charset=utf-8",
},
});
}
Deno.serve(handler);
Deno.connectTls
建立外連 TLS 連線。
函式定義與 Deno 相同,限制為 hostname 不能為 localhost 或空值。
function Deno.connectTls(options: ConnectTlsOptions): Promise<Conn>
範例
async function handler(_req) {
// Make a TLS connection to example.com
const connection = await Deno.connectTls({
port: 443,
hostname: "example.com",
});
// Send raw HTTP GET request.
const request = new TextEncoder().encode(
"GET / HTTP/1.1\nHost: example.com\r\n\r\n",
);
const _bytesWritten = await connection.write(request);
// Read 15 bytes from the connection.
const buffer = new Uint8Array(15);
await connection.read(buffer);
connection.close();
// Return the bytes as plain text.
return new Response(buffer, {
headers: {
"content-type": "text/plain;charset=utf-8",
},
});
}
Deno.serve(handler);