nim-libp2p/testwebrtc.nim

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

45 lines
1.3 KiB
Nim
Raw Permalink Normal View History

2023-10-13 16:07:52 +00:00
import chronos, libp2p, libp2p/transports/webrtctransport
2024-02-05 16:44:35 +00:00
import stew/byteutils
proc echoHandler(conn: Connection, proto: string) {.async.} =
defer: await conn.close()
while true:
try:
echo "\e[35;1m => Echo Handler <=\e[0m"
2024-02-15 15:10:20 +00:00
var xx = newSeq[byte](1024)
let aa = await conn.readOnce(addr xx[0], 1024)
xx = xx[0..<aa]
let msg = string.fromBytes(xx)
2024-02-05 16:44:35 +00:00
echo " => Echo Handler Receive: ", msg, " <="
echo " => Echo Handler Try Send: ", msg & "1", " <="
2024-02-15 15:10:20 +00:00
await conn.write(msg & "1")
2024-02-05 16:44:35 +00:00
except CatchableError as e:
echo " => Echo Handler Error: ", e.msg, " <="
break
2023-10-13 16:07:52 +00:00
proc main {.async.} =
2024-11-08 14:06:56 +00:00
let ma = MultiAddress.init("/ip4/127.0.0.1/udp/4242/webrtc-direct/certhash/uEiDDq4_xNyDorZBH3TlGazyJdOWSwvo4PUo5YHFMrvDE8g")
echo ma
2023-10-13 16:07:52 +00:00
let switch =
SwitchBuilder.new()
2024-11-08 14:06:56 +00:00
.withAddress(ma.tryGet()) #TODO the certhash shouldn't be necessary
2023-10-13 16:07:52 +00:00
.withRng(crypto.newRng())
.withMplex()
2024-02-15 15:10:20 +00:00
.withYamux()
2023-10-13 16:07:52 +00:00
.withTransport(proc (upgr: Upgrade): Transport = WebRtcTransport.new(upgr))
.withNoise()
.build()
2024-02-05 16:44:35 +00:00
let
codec = "/echo/1.0.0"
proto = new LPProtocol
proto.handler = echoHandler
proto.codec = codec
switch.mount(proto)
2023-10-13 16:07:52 +00:00
await switch.start()
2024-02-05 16:44:35 +00:00
echo "\e[31;1m", $(switch.peerInfo.addrs[0]), "/p2p/", $(switch.peerInfo.peerId), "\e[0m"
2023-10-13 16:07:52 +00:00
await sleepAsync(1.hours)
waitFor main()