Skip to content

Instantly share code, notes, and snippets.

@dom96
Created February 15, 2014 22:21
Show Gist options
  • Save dom96/039a0240dcc2625da7d7 to your computer and use it in GitHub Desktop.
Save dom96/039a0240dcc2625da7d7 to your computer and use it in GitHub Desktop.
import asyncio2, sockets2
var disp = newDispatcher()
var msgCount = 0
const
swarmSize = 50
messagesToSend = 100
var clientCount = swarmSize
proc sendMessages(disp: PDispatcher, client: TSocketHandle): PFuture[int] {.async.} =
for i in 0 .. <messagesToSend:
discard await disp.send(client, "Message " & $i & "\c\L")
proc launchSwarm(disp: PDispatcher, port: TPort): PFuture[int] {.async.} =
for i in 0 .. <swarmSize:
var sock = socket()
discard await disp.connect(sock, "localhost", port)
var msgFut = sendMessages(disp, sock)
msgFut.callback =
proc () =
sock.close()
clientCount.dec
proc readMessages(disp: PDispatcher, client: TSocketHandle): PFuture[int] {.async.} =
while true:
var line = await disp.recvLine(client)
if line == "":
client.close()
break
else:
if line.startswith("Message "):
msgCount.inc
else:
doAssert false
proc createServer(disp: PDispatcher, port: TPort): PFuture[int] {.async.} =
var server = socket()
server.bindAddr(port)
server.listen()
while true:
var client = await disp.accept()
discard readMessages(disp, client)
discard disp.createServer(TPort(10335))
discard disp.launchSwarm(TPort(10335))
while true:
disp.poll()
if clientCount == 0: break
echo msgCount
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment