Advertisement
Guest User

Untitled

a guest
Oct 25th, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Nim 2.03 KB | None | 0 0
  1. # This is just an example to get you started. A typical binary package
  2. # uses this file as the main entry point of the application.
  3.  
  4. import  strformat, tables, json, strutils, sequtils, hashes, net, asyncdispatch, asyncnet, os, strutils, parseutils, deques, options, net
  5.  
  6. type ForwardOptions = object
  7.   listenAddr*: string
  8.   listenPort*: Port
  9.   toAddr*: string
  10.   toPort*: Port
  11.  
  12. type Forwarder = object of RootObj
  13.   options*: ForwardOptions
  14.  
  15. proc processClient(this: ref Forwarder, client: AsyncSocket) {.async.} =
  16.   let remote = newAsyncSocket(buffered=false)
  17.   await remote.connect(this.options.toAddr, this.options.toPort)
  18.  
  19.   proc clientHasData() {.async.} =
  20.     while not client.isClosed and not remote.isClosed:
  21.       echo "in client has data loop"
  22.       let data = await client.recv(1024)
  23.       echo "got data: " & data
  24.       if data.len>0:
  25.         await remote.send(data)
  26.     client.close()
  27.     remote.close()
  28.  
  29.   proc remoteHasData() {.async.} =
  30.     while not remote.isClosed and not client.isClosed:
  31.       echo " in remote has data loop"
  32.       let data = await remote.recv(1024)
  33.       echo "got data: " & data
  34.       await client.send(data)
  35.     client.close()
  36.     remote.close()
  37.  
  38.   try:
  39.     asyncCheck clientHasData()
  40.     asyncCheck remoteHasData()
  41.   except:
  42.     echo getCurrentExceptionMsg()
  43.  
  44. proc serve(this: ref Forwarder) {.async.} =
  45.   var server = newAsyncSocket(buffered=false)
  46.   server.setSockOpt(OptReuseAddr, true)
  47.   server.bindAddr(this.options.listenPort, this.options.listenAddr)
  48.   echo fmt"Started tcp server... {this.options.listenAddr}:{this.options.listenPort} "
  49.   server.listen()
  50.  
  51.   while true:
  52.     let client = await server.accept()
  53.     echo "..Got connection "
  54.  
  55.     asyncCheck this.processClient(client)
  56.  
  57. proc newForwarder(opts: ForwardOptions): ref Forwarder =
  58.   result = new(Forwarder)
  59.   result.options = opts
  60.  
  61. let opts = ForwardOptions(listenAddr:"127.0.0.1", listenPort:11000.Port, toAddr:"127.0.0.1", toPort:8000.Port)
  62. var f = newForwarder(opts)
  63. asyncCheck f.serve()
  64. runForever()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement