Using connection pools in a websocket server with HTTP.jl

Hi all-

I have two clients connected to a websocket server in HTTP.jl. I would like to do the following: send data from client 1 to the websocket server, process the data, send the processed data to client 2. Here is the barebones setup:

@async HTTP.WebSockets.listen("127.0.0.1", UInt16(8081)) do ws
 while !eof(ws)
    #read incoming data from client 1
    incomming_data = readavailable(ws)

    #process incomming_data
    #process the data here ...
    processed_data = "processed data"

    #send the processed data to client 2
    write(ws, processed_data)
 end
end

Currently, the write function sends the processed data back to client 1 instead of client 2. Networking is fairly new to me, but I suspect that the ws object passed to the write function contains information about the connection, perhaps a connection ID. Based on the documentation, I see that there is a connection pool that can be referenced with HTTP.ConnectionPool.pool. When I print it out from the listen function, it appears to be empty:

Array{HTTP.ConnectionPool.Connection}((0,))

Is there a way to use something like a connection ID to control the flow of information? Thanks.

I figured out a solution. Each client has an initial connection message containing the id. The id and websocket object are stored in a dictionary, which is used to send the processed data from client1 to client2. Perhaps there is a more scalable and elegant approach but for a simple situation this works.

clients = Dict{Symbol, HTTP.WebSockets.WebSocket}()
@async HTTP.WebSockets.listen("127.0.0.1", UInt16(8081)) do ws
 while !eof(ws)
    #read incoming data from client 1
    incomming_data = readavailable(ws)
    #Establish client IDs with initial connection messages
    if incomming_data == "client1"
      clients[:client1] = ws
      continue
    end
    if incomming_data == "client2"
      clients[:client2] = ws
      continue
    end
    #process incomming_data
    #process the data here ...
    processed_data = "processed data"
    #send the processed data to client 2 from client 1
    if clients[:client1] == ws
      write(clients[:client2], processed_data)
    end
 end
end
2 Likes