treeform / ws

Simple WebSocket library for Nim.
MIT License
254 stars 23 forks source link

Poor performance while sending data through opened sockets #44

Closed JeysonFlores closed 2 years ago

JeysonFlores commented 2 years ago

Hello I was trying to implement some sort of pub/sub service using this library and jester. I managed to write this piece of code:

import asyncdispatch, jester
import ws, ws/jester_extra
import std/strformat                                          
import std/sets
include types/ws_hash #This is just a file I wrote that makes the WebSocket type hashable and makes it able to use it with a HashSet

var socketPool = initHashSet[WebSocket]()

router cnsRouter:
  get "/count":
    resp fmt"{socketPool.len} connection(s)"

  get "/pub":
    var count = 0
    for socket in socketPool:
        await socket.send("Test message")
        count += 1

    resp fmt"Sent {count} msg(s)"

  get "/sub":
    var ws = await newWebSocket(request)
    socketPool.incl(ws)

    try:
      while ws.readyState == Open:
        discard await ws.receiveStrPacket()
    except:
      echo "Connection closed"
    finally:    
      socketPool.excl(ws)

    resp ""

It works fine however it takes too much time to broadcast the message to all opened sockets. In my computer takes almost 1s per connection to deliver the message and it seems it goes increasing by 1s the request time on the /pub endpoint if you keep opening connections to the /sub endpoint. Is there any particular reason why this happens? I'm aware this is a community project and it can have its drawbacks but I think 1s per connection is an excessive amount of time. Maybe I'm doing something wrong? I'll gladly appreciate all the comments. Thanks

JeysonFlores commented 2 years ago

Fixed with await all(futures)