Hi all,
I copied the following code from this Discourse response about linking Julia and node.js. I’m very new to the idea of both tasks and sockets, and although I’ve got the code working perfectly for my use-case, I wanted to gain a better understanding of what is actually happening.
# Some setup code
@async begin
server = listen(pipe)
while true
sock = accept(server)
@async while isopen(sock)
input = JSON.parse(sock)
# Some code that does something to input
end
end
end
# Some following code
My understanding is this:
The first @async
treats everything in the begin
clause as a function, wraps it in a Task
and immediately starts executing the Task
, as well as allowing the main routine to proceed to any code after the begin
clause ends. Within this first Task
, a PipeServer
is created and stored in the variable server
by calling listen
on the UNIX domain socket denoted by pipe
. Then a while true
loop is initiated. I think the purpose of this loop is to make sure that the first Task
doesn’t finish, and we keep listening on the UNIX domain socket indefinitely. I think (hope) I understand everything up to this point. But I don’t understand the next bit, even though it works perfectly for me.
On the first iteration of the while true
loop, we call accept(server)
. My understanding is that this creates an open IOStream
and stores it in sock
. Normally, I would have thought that sock
would be open immediately after this call. Is this right? Or is sock
only “open” when some data is sent through the domain socket?
If it is open immediately after the call, then I definitely don’t understand what happens next. We create a second Task
that iterates on while isopen(sock)
. This task will keep running, since sock
is open, and since it is an @async
task, our routine can also continue on to the next iteration of the while true
loop, where we create another sock
? This doesn’t sound right at all. Also, how does the code in that second Task
, in the while isopen(sock)
line, know when data is coming through and it has to run, versus when no data is coming through and it shouldn’t run?
So maybe sock
is not open immediately after the accept(server)
call, but this also defies everything I currently understand about how an IOStream
works.
As you can see, I’m going in circles here.
I apologize for the rather wordy post, but if anyone can take the time to explain what is actually happening here in simple terms I would be very appreciative.
Cheers and thanks,
Colin