blob: 5165b0f06e79cab8d4e000437d88fc39364ff386 (
plain) (
blame)
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
|
discard """
file: "tasyncawait.nim"
output: "5000"
"""
import asyncdispatch, rawsockets, net, strutils, os
var msgCount = 0
const
swarmSize = 50
messagesToSend = 100
var clientCount = 0
proc sendMessages(client: TAsyncFD) {.async.} =
for i in 0 .. <messagesToSend:
await send(client, "Message " & $i & "\c\L")
proc launchSwarm(port: TPort) {.async.} =
for i in 0 .. <swarmSize:
var sock = newAsyncRawSocket()
await connect(sock, "localhost", port)
await sendMessages(sock)
closeSocket(sock)
proc readMessages(client: TAsyncFD) {.async.} =
while true:
var line = await recvLine(client)
if line == "":
closeSocket(client)
clientCount.inc
break
else:
if line.startswith("Message "):
msgCount.inc
else:
doAssert false
proc createServer(port: TPort) {.async.} =
var server = newAsyncRawSocket()
block:
var name: Sockaddr_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.SocketHandle, cast[ptr SockAddr](addr(name)),
sizeof(name).Socklen) < 0'i32:
raiseOSError(osLastError())
discard server.SocketHandle.listen()
while true:
var client = await accept(server)
asyncCheck readMessages(client)
# TODO: Test: readMessages(disp, await disp.accept(server))
asyncCheck createServer(TPort(10335))
asyncCheck launchSwarm(TPort(10335))
while true:
poll()
if clientCount == swarmSize: break
assert msgCount == swarmSize * messagesToSend
echo msgCount
|