在Golang中,TCPConn.Write/Read会返回哪种错误?

huangapple go评论71阅读模式
英文:

In golang what error will TCPConn.Write/Read return?

问题

在Golang中,你可以通过以下方式处理TCPConn.Read/Write返回的错误:

  1. 使用io包中的ReadFullWriteFull函数来确保读取和写入指定长度的数据。这些函数会在读取/写入不足指定长度的情况下返回错误。

  2. 使用bufio包中的ReaderWriter来进行缓冲读写操作。这些类型提供了更高级的接口,可以处理部分读写的情况,并提供了更多的错误信息。

  3. 在进行读写操作之前,可以使用SetReadDeadlineSetWriteDeadline方法设置读写超时时间。如果在指定的时间内没有完成读写操作,将返回超时错误。

  4. 对于特定的错误类型,可以使用类型断言来判断错误的具体类型,并根据需要进行处理。例如,可以使用net包中定义的OpError类型来判断是否是连接关闭的错误。

需要注意的是,以上只是一些处理错误的常见方法,具体的处理方式还取决于你的应用场景和需求。

英文:

In golang, how would you handle error return by TCPConn.Read/Write?
this document did not say anything about read/write errors.

答案1

得分: 8

TCPConn上进行ReadWrite操作可能会返回大部分由操作系统、硬件和驱动程序组合产生的错误,以及一些net包错误和适用时的io.EOF。因此,你需要知道要查找哪些错误,并且如何处理它们。网络API的每一层,甚至是伯克利套接字API,都是有缺陷的抽象,如果不了解实际的套接字和网络协议的工作原理,就无法充分利用它。

通常,你只需要关注io.EOF,它在连接关闭时由Conn.Read返回。在TCP套接字上,这相当于在阻塞连接上接收到0字节的recv返回。

其他你可以处理的错误通常被包装在一个net.Error中,它提供了Temporary()Timeout()方法。通常,真正的错误类型是*net.OpError,它可以提供关于错误发生时间的更多信息,并封装操作返回的实际错误。

英文:

Read and Write on a TCPConn could return most of errors that your combination of OS, hardware and drivers could return, along with some net package errors, and io.EOF when applicable. So it's really up to you to know what errors to look for, and how to handle them. Every layer of network API, even the berkeley socket api, is a leaky abstraction, and you can't make full use of it without understanding how the actual sockets and network protocols work.

Usually you only need be concerned with io.EOF, which is returned by Conn.Read when the connection is closed. On a TCP socket, this is the equivalent of recv returning 0 bytes on a blocking connection.

Any other errors that you could handle are usually wrapped in a net.Error, which provides the Temporary() and Timeout() methods. Often the real error type is a *net.OpError, which can provide even more information about when the error occurred, as well as encapsulate the actual error returned by the operation.

huangapple
  • 本文由 发表于 2015年7月17日 18:16:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/31473522.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定