Created
October 13, 2024 14:41
-
-
Save SerJaimeLannister/f5cabd4dcb71868933b0a2e904e72995 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { readStdin } from "./readlines.ts"; | |
| import { BlobTicket, Iroh } from "npm:@number0/iroh"; | |
| const prompt = 'Type a message to share (or "exit" to quit): '; | |
| async function* inputLoop() { | |
| for await (const line of readStdin()) { // Use the new readStdin generator | |
| yield line; // Yield each line as it is read | |
| } | |
| } | |
| async function runServer(node: Iroh) { | |
| console.log("Server mode. Type messages to share, or 'exit' to quit."); | |
| await Deno.stdout.write(new TextEncoder().encode(prompt)); | |
| for await (const line of inputLoop()) { | |
| if (line.toLowerCase() === "exit") { | |
| break; | |
| } | |
| const data = Array.from(new TextEncoder().encode(line)); | |
| const result = await node.blobs.addBytes(data); | |
| const ticket = await node.blobs.share( | |
| result.hash, | |
| result.format, | |
| "RelayAndAddresses", | |
| ); | |
| console.log( | |
| `Message shared. To retrieve, run:\ndeno run prototype1.ts ${ticket.toString()}`, | |
| ); | |
| await Deno.stdout.write(new TextEncoder().encode(prompt)); | |
| } | |
| } | |
| async function runClient(node: Iroh, ticketString: string) { | |
| const ticket = BlobTicket.fromString(ticketString); | |
| console.log( | |
| `Fetching hash '${ticket.hash}' from node: '${ticket.nodeAddr.nodeId.toString()}'`, | |
| ); | |
| await node.blobs.download( | |
| ticket.hash, | |
| ticket.asDownloadOptions(), | |
| (_err) => {}, | |
| ); | |
| const data = await node.blobs.readToBytes(ticket.hash); | |
| console.log( | |
| "Retrieved message:", | |
| new TextDecoder().decode(new Uint8Array(data)), | |
| ); | |
| } | |
| if (import.meta.main) { | |
| const node = await Iroh.memory(); | |
| if (Deno.args.length > 0) { | |
| // Client mode | |
| await runClient(node, Deno.args[0]); | |
| } else { | |
| // Server mode | |
| await runServer(node); | |
| } | |
| Deno.exit(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment