NimProgrammingBook
NimProgrammingBook copied to clipboard
maybe an effecient way to broadcast message in the chat server application
first, i'd like to thank you for this awesome book, i have learnt a lot from it.
while reading the section about implementing a chat server application, i think await asyncfutures.all clientSendFutures will be more effecient than the for ... await.
proc processClient(client: AsyncSocket) {.async.} =
while true:
let line = await client.recvLine()
if line.len == 0: break
for c in clients:
await c.send(line & "\c\L")
->
let sendFuts = collect:
for c in clients:
c.send(line & "\c\L")
await all sendFuts
by using asyncdispatch.all, it turns linear sending to concurrent
Thank you very much for reading my book!
Your remarks seems to be true. Actually the server code was based on the example in the Nim API docs, and the client was inspired by code of the book of Mr. Picheta that I read in late 2016 as pre-print. The async/await frame work has evolved since then. Actually I have never used the async/await pattern in my own code before, as I do no web stuff myself. That is the reason why this section came so late to the book, I generally prefer explaining things that I use a lot myself. But of course async/await is important for some people, and not all people may also have the book of Mr. Picheta, so I added the async/await section finally.
thanks for the reply, i did not notice that.
i looked it further, IMHO, the example in nim api doc is hard to understand, the lifetime of each task is not clear. so i spent some times to write up another impl which is based on my past expirements using python's trio.
I think we can let this issue open, I definitely will check your remarks. Note that there is also an alternative async implementation available from Status, called chronos, see https://github.com/status-im/nim-chronos
i have heard about chronos some times and once again, finally i tried out it just now; it's amazing! all my doubts that occured during using std/asyncdispatch have been solved: cancellation, checkpoint/switch-task without fd required. it is unbelievable that a third-party module is more mature and good shaped than a std module.