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 . } =
let switch =
SwitchBuilder . new ( )
. withAddress ( MultiAddress . init ( " /ip4/127.0.0.1/udp/4242/webrtc-direct/certhash/uEiDDq4_xNyDorZBH3TlGazyJdOWSwvo4PUo5YHFMrvDE8g " ) . tryGet ( ) ) #TODO the certhash shouldn't be necessary
. 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 ( )