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')
添加回答
举报