如何在Julia中停止TCP服务器?

如何在Julia中停止TCP服务器?,tcp,julia,tcplistener,Tcp,Julia,Tcplistener,TCP示例 @async begin server = listen(2000) while true sock = accept(server) println("Hello World\n") end end 要关闭连接,需要调用close方法: close(sock) 如何阻止听众 close(server) #LoadError: accept: software caused connection abort (ECONNABORTED) 与其继续

TCP示例

@async begin
  server = listen(2000)
    while true
    sock = accept(server)
    println("Hello World\n")
  end
end
要关闭连接,需要调用
close
方法:

close(sock)
如何阻止听众

close(server) #LoadError: accept: software caused connection abort (ECONNABORTED)

与其继续评论,以下是我认为你可能想做的:

从julia REPL:

julia> server = listen(2000)
Base.TCPServer(active)

julia> @async begin
         while true
           sock = accept(server)
           print(readstring(sock))
         end
       end
从另一个终端:

~ $ nc localhost 2000
Hello from the other terminal
[Ctrl-D]   % i.e. signal end of file. this closes the connection
在julia repl中,发送EOF信号后,您将看到打印的“来自另一个终端的Hello”,否则julia提示将正常继续。如果从netcat终端重复此过程,您将再次看到REPL中打印的消息,因为套接字在while循环中不断重新激活

理想情况下,如果您想关闭整个系统,您可以先
关闭(sock)
,然后
关闭(服务器)
。但是,您不能直接关闭套接字,因为它处于“while”循环中,并且不断被重新激活,并且您无法直接访问变量“sock”

因此,您只能关闭服务器,完全可能会发生错误。所以,在试块中捕捉它

编辑:对不起,我的错,异常与套接字有关,而不是与服务器有关,因此您需要将其包装在异步块内的try-catch块中:

@async begin
     while true
       try
         sock = accept(server)
         print(readstring(sock))
       catch ex
         print("exiting while loop")
         break
       end 
     end
   end

我不能复制这个。在执行一个正常(非
@async
)示例时,
close(sock)
close(server)
都可以正常工作(julia 0.6.0)。在上面的例子中,我无法访问服务器和sock来关闭它们。也许您是想在
@async
任务之外定义服务器和套接字?只有在我尝试关闭服务器而没有先关闭套接字时,我才会收到您描述的错误。(如果您使用
server=listen(2000),则REPL中可能会出现这种情况)
在异步块之外。由于您正在打印自己的字符串,而不是从流中读取,因此流永远不会关闭。也许您应该尝试一个更好的示例?另外,请注意,该错误不一定是坏事。当服务器意外关闭时,它只会被try块捕获,但您完全可以这样做“尝试关闭(服务器)捕获“等等。我想我在这里会注意到,OP可能在
@async
中包含了
listen
语句,因为在中的示例中就是这样。顺便说一句,这个答案确实帮了我很大的忙,尽管这让我感到有点不舒服,因为我们为了结束任务而故意造成错误。