Skip to content

Commit cc61161

Browse files
committed
graceful closing of ws connection
1 parent a97eec4 commit cc61161

1 file changed

Lines changed: 12 additions & 7 deletions

File tree

src/WebChannels.jl

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ function unsubscribe_disconnected_clients() :: ChannelClientsCollection
171171
unsubscribe_client(channel_client)
172172
end
173173

174-
@async purge_unnecessary_message_queue() |> errormonitor
174+
@async(purge_unnecessary_message_queue()) |> errormonitor
175175

176176
CLIENTS
177177
end
@@ -243,7 +243,7 @@ function broadcast(channels::Union{ChannelName,Vector{ChannelName}},
243243

244244
isempty(SUBSCRIPTIONS) && return false
245245

246-
@async unsubscribe_disconnected_clients() |> errormonitor
246+
@async(unsubscribe_disconnected_clients()) |> errormonitor
247247

248248
for channel in channels
249249
if ! haskey(SUBSCRIPTIONS, channel)
@@ -315,8 +315,7 @@ function message(client::ClientId, msg::String)
315315
# retrieve the message queue or set it up if not present
316316
q, _ = get!(MESSAGE_QUEUE, client) do
317317
queue = Channel{Tuple{String, Channel{Int}}}(10)
318-
handler = @async while true
319-
message, future = take!(queue)
318+
handler = @async(for (message, future) in queue
320319
nbytes = 0
321320
try
322321
nbytes = Sockets.send(ws, message)
@@ -326,8 +325,11 @@ function message(client::ClientId, msg::String)
326325
put!(future, nbytes)
327326
end
328327
# Self-terminate when the socket is closed to avoid orphaned tasks.
329-
HTTP.WebSockets.isclosed(ws) && break
330-
end |> errormonitor
328+
if HTTP.WebSockets.isclosed(ws)
329+
@info "closing ws"
330+
break
331+
end
332+
end) |> errormonitor
331333

332334
queue, handler
333335
end
@@ -356,8 +358,11 @@ end
356358
function delete_queue!(d::Dict, client::UInt)
357359
queue, handler = pop!(MESSAGE_QUEUE, client, (nothing, nothing))
358360
if queue !== nothing
359-
killtask(handler) |> errormonitor
361+
close(queue)
362+
# close(queue) will normally cause the handler task to exit, but we add a killtask to be sure.
363+
@async(killtask(handler, wait_for_started_duration = 0.1) |> errormonitor)
360364
end
365+
return d
361366
end
362367

363368
"""

0 commit comments

Comments
 (0)