2 回答

TA貢獻1966條經驗 獲得超4個贊
使用 Deno.listen
創建服務器,使用 Deno.connect
連接到該服務器。
服務器/客戶端的一個簡單示例是:tcp
服務器.js
const encoder = new TextEncoder();
const decoder = new TextDecoder();
const listener = Deno.listen({ port: 8080 });
console.log("listening on 0.0.0.0:8080");
for await (const conn of listener) {
// Read message
const buf = new Uint8Array(1024);
await conn.read(buf);
console.log('Server - received:', decoder.decode(buf))
// Respond
await conn.write(encoder.encode('pong'))
conn.close();
}
客戶端.js
const encoder = new TextEncoder();
const decoder = new TextDecoder();
const conn = await Deno.connect({ hostname: "127.0.0.1", port: 8080 })
// Write to the server
await conn.write(encoder.encode('ping'));
// Read response
const buf = new Uint8Array(1024);
await conn.read(buf);
console.log('Client - Response:', decoder.decode(buf))
conn.close();
您可以從此處進行構建。對于聊天服務器,您將保持連接打開狀態,并發送多條消息。

TA貢獻1818條經驗 獲得超7個贊
好吧,經過更多的嘗試,這是我的TCP聊天服務器:
const server = Deno.listen({ port: 8000 });
console.log("tcp server listening on port 8000");
const connections: Deno.Conn[] = [];
for await (const connection of server) {
// new connection
connections.push(connection);
handle_connection(connection);
}
async function handle_connection(connection: Deno.Conn) {
let buffer = new Uint8Array(1024);
while (true) {
const count = await connection.read(buffer);
if (!count) {
// connection closed
const index = connections.indexOf(connection);
connections.splice(index, 1);
break;
} else {
// message received
let message = buffer.subarray(0, count);
for (const current_connection of connections) {
if (current_connection !== connection) {
await current_connection.write(message);
}
}
}
}
}
代碼看起來與 Node 版本完全不同。也就是說,TCP不維護消息邊界,Deno版本通過讀取緩沖區來明確這一點。這類似于 Rust 和模塊處理 TCP 的方式。實際上,我不太確定事件在Node中代表什么;它似乎只是來自TCP流的任意長度的數據片段。Uint8Arraystd::nettokio::netsocket.on('data')
添加回答
舉報