在Go中断开套接字时,我是否可以知道它是好还是坏? [英] When a socket is disconnected in Go, can I know if it was a good or bad close?

查看:214
本文介绍了在Go中断开套接字时,我是否可以知道它是好还是坏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我打开与服务器的连接,如:

Say I open a connection to a server like:

conn, _ := net.DialTimeout("tcp", "127.0.0.1:2121", 10000000)

我做了一些事情,然后打电话给

and I do some stuff and then call

conn.Close()

这是选项1.但是如果我不在conn上调用Close并且只是调用

that's option 1. But what if I don't call Close on the conn and just call

os.Exit(1)

让连接保持打开状态。这是选项2.即我试图模拟用户上传文件并到达结尾并真正关闭连接...或者结束正在写入套接字的流但从未正式关闭它。

leaving the connection still open. That's option 2. i.e. I'm trying to simulate a user uploading a file and either reaching the ending and really Closing the connection... or ending the stream being writen to the socket but never officially closing it.

回到服务器端,无论如何都要告诉发生了哪个事件?好的关闭还是坏的?

Back on the server side, is there anyway to tell which event happened? The good Close or the bad one?

net.Listener 是否有某种回调让我知道。因为当我打电话时:

Does net.Listener have like some sort of callback to let me know. Because when I just call:

n, err := serverConn.Read()

无论是好还是坏,我都会得到一个EOF错误。

I get an EOF err in either case, good or bad.

推荐答案

我知道这不是一个答案,但我无法评论,这是非常令人沮丧的,因为我试图建议编辑只是问这个问题,这个应用告诉我,我不能之后我写了它。请怜悯。

I know this isn't an answer but I can't comment and it's extremely frustrating because I tried to suggest an edit to just ask this question, and this app told me I couldn't after I wrote it. Please be merciful.

@EJP你能提供消息来源吗?我知道你所说的对于C来说是正确的,但几乎所有人都可以安全地让GC处理在Go中程序终止时关闭。我打赌它与操作系统无关(但我可能会弄错),因为GC可能会为你正确处理套接字(请参阅所有解释你可以通过省略'关闭'来节省时间的库,如果程序执行正在终止)。我正在考虑问一个有多远的问题,但是我遇到了一个它没有处理清理的情况(并且肯定不在标准的lib中)。

@EJP Can you provide a source? I know what you're saying is true for C but almost literally everything is safe to let the GC handle for closes on program termination in Go. I'd wager it has nothing to do with the OS (but I could be mistaken) as the GC probably handles closing the socket properly for you anyways (see all the libraries which explain "you can save time by ommiting 'Close' if the program execution is terminating"). I'm considering asking a question of how far that goes but I've run into exactly one case where it doesn't handle the cleanup (and it's certainly not in a standard lib).

这篇关于在Go中断开套接字时,我是否可以知道它是好还是坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆