1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
discard """
file: "tasyncawait.nim"
cmd: "nimrod cc --hints:on $# $#"
output: "5000"
"""
import asyncdispatch, rawsockets, net, strutils, os
var disp = newDispatcher()
var msgCount = 0
const
swarmSize = 50
messagesToSend = 100
var clientCount = 0
proc sendMessages(disp: PDispatcher, client: TSocketHandle) {.async.} =
for i in 0 .. <messagesToSend:
await disp.send(client, "Message " & $i & "\c\L")
proc launchSwarm(disp: PDispatcher, port: TPort) {.async.} =
for i in 0 .. <swarmSize:
var sock = disp.socket()
#disp.register(sock)
await disp.connect(sock, "localhost", port)
when true:
await sendMessages(disp, sock)
disp.close(sock)
else:
# Issue #932: https://github.com/Araq/Nimrod/issues/932
var msgFut = sendMessages(disp, sock)
msgFut.callback =
proc () =
disp.close(sock)
proc readMessages(disp: PDispatcher, client: TSocketHandle) {.async.} =
while true:
var line = await disp.recvLine(client)
if line == "":
disp.close(client)
clientCount.inc
break
else:
if line.startswith("Message "):
msgCount.inc
else:
doAssert false
proc createServer(disp: PDispatcher, port: TPort) {.async.} =
var server = disp.socket()
#disp.register(server)
block:
var name: TSockaddr_in
when defined(windows):
name.sin_family = toInt(AF_INET).int16
else:
name.sin_family = toInt(AF_INET)
name.sin_port = htons(int16(port))
name.sin_addr.s_addr = htonl(INADDR_ANY)
if bindAddr(server, cast[ptr TSockAddr](addr(name)),
sizeof(name).TSocklen) < 0'i32:
osError(osLastError())
discard server.listen()
while true:
var client = await disp.accept(server)
readMessages(disp, client)
# TODO: Test: readMessages(disp, await disp.accept(server))
disp.createServer(TPort(10335))
disp.launchSwarm(TPort(10335))
while true:
disp.poll()
if clientCount == swarmSize: break
assert msgCount == swarmSize * messagesToSend
echo msgCount
|