Setting read/write deadlines
If you do not want to wait indefinitely for a connected host to send data, or for the connected host to receive the data you sent, you have to set a deadline.
How to do it...
Depending on your specific protocol, you can set read or write deadlines, and you may choose to set these deadlines for individual I/O operations, or globally:
- Set the deadline before the operation:
conn.SetDeadline(time.Now().Add(timeoutSeconds * timeSecond)) if n, err:=conn.Read(data); err!=nil { if errors.Is(err, os.ErrDeadlineExceeded) { // Deadline exceeded. } else { // Some other error } }
- If you will continue using the connection after a deadline is exceeded, you have to reset the deadline:
conn.SetDeadline(time.Time{})
Or, set a new deadline with a time in the future.