Guest User

Untitled

a guest
Feb 14th, 2020
82
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import asyncdispatch, asyncnet, locks
  2.  
  3. from osproc import countProcessors
  4.  
  5. import httputils
  6.  
  7. type
  8.   Server = ref object
  9.     socket: AsyncSocket
  10.  
  11. proc newServer*(): Server = new result
  12.  
  13. proc close*(server: Server) =
  14.   server.socket.close()
  15.  
  16. proc sendResp*(socket: AsyncSocket, code: HttpCode) {.async.} =
  17.   await socket.send("HTTP/1.1 " & $code & "\c\L" &
  18.                             "Content-Length: " & $(($code).len + 2) & "\c\L\c\L" &
  19.                             $code & "\c\L")
  20.  
  21. proc processMessage(server: Server, csocket: AsyncSocket) {.async.} =
  22.  
  23.   echo "threadid: " & $getThreadId()
  24.   while not csocket.isClosed():
  25.     try:
  26.       let line = await csocket.recvLine()
  27.  
  28.       if line.len == 0:
  29.         csocket.close()
  30.         break
  31.  
  32.       await csocket.sendResp(Http200)
  33.     except Exception as e:
  34.       echo "Failed processClient(): " & e.msg
  35.       break
  36.  
  37. proc loop(server: Server, port = 5000){.async.} =
  38.   server.socket = newAsyncSocket(buffered = false)
  39.   server.socket.setSockOpt(OptReuseAddr, true)
  40.   server.socket.setSockOpt(OptReusePort, true)
  41.   server.socket.bindAddr(port.Port)
  42.   server.socket.listen()
  43.  
  44.   while true:
  45.     let (netAddr, clientSocket) = await server.socket.acceptAddr()
  46.     echo "accepted connection from " & netAddr
  47.     asyncCheck processMessage(server, clientSocket)
  48.  
  49.  
  50. proc runServer() =
  51.   let svr = newServer()
  52.   waitFor loop(svr)
  53.   svr.close()
  54.  
  55. proc start*() =
  56.   let cores = countProcessors()
  57.   var threads = newSeq[Thread[void]](cores)
  58.   for i in 0 ..< cores:
  59.     createThread[void](threads[i], runServer)
  60.   echo("Listening on port 5000") # This line is used in the tester to signal readiness.
  61.   joinThreads(threads)
RAW Paste Data