亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何用Deno編寫TCP聊天服務器?

如何用Deno編寫TCP聊天服務器?

拉莫斯之舞 2022-08-18 15:52:05
真正讓我確信Node強大功能的演示之一是Ryan Dahl在這段視頻中介紹的簡單TCP聊天服務器:https://www.youtube.com/watch?v=jo_B4LTHi3I&t=28m23s演示中的代碼如下所示:const net = require('net');const server = net.createServer();const sockets = [];server.on('connection', (socket) => {  sockets.push(socket);  socket.on('data', (message) => {    for (const current_socket of sockets) {      if (current_socket !== socket) {        current_socket.write(message);      }    }  });  socket.on('end', () => {    const index = sockets.indexOf(socket);    sockets.splice(index, 1);  });});server.listen(8000, () => console.log('tcp server listening on port 8000'));我在Deno網站上找到的唯一TCP示例是一個回顯服務器,如下所示:const listener = Deno.listen({ port: 8080 });console.log("listening on 0.0.0.0:8080");for await (const conn of listener) {  Deno.copy(conn, conn);}它很好,很緊湊,但我無法使用 和 方法將此示例轉換為 TCP 聊天服務器。任何幫助將不勝感激!我也認為這將是一個有用的例子添加到網站。Deno.Connreadwrite
查看完整描述

2 回答

?
慕標5832272

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();


您可以從此處進行構建。對于聊天服務器,您將保持連接打開狀態,并發送多條消息。


查看完整回答
反對 回復 2022-08-18
?
qq_笑_17

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')


查看完整回答
反對 回復 2022-08-18
  • 2 回答
  • 0 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號