io.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package tcp
  2. import (
  3. "bufio"
  4. "net"
  5. "time"
  6. )
  7. func errTimeout(err error) bool {
  8. if opErr, ok := err.(*net.OpError); ok {
  9. if opErr.Temporary() || opErr.Timeout() {
  10. return true
  11. }
  12. }
  13. return false
  14. }
  15. // Write tcp write
  16. func Write(conn *net.TCPConn, timeout time.Duration, data []byte) (n int, isTimeout bool, err error) {
  17. conn.SetWriteDeadline(time.Now().Add(timeout))
  18. n, err = conn.Write(data)
  19. if err != nil {
  20. isTimeout = errTimeout(err)
  21. }
  22. return
  23. }
  24. // Read tcp reads data into p.
  25. // It returns the number of bytes read into p.
  26. // The bytes are taken from at most one Read on the underlying Reader,
  27. // hence n may be less than len(p).
  28. // To read exactly len(p) bytes, use io.ReadFull(b, p).
  29. // At EOF, the count will be zero and err will be io.EOF.
  30. func Read(conn *net.TCPConn, timeout time.Duration, p []byte) (n int, isTimeout bool, err error) {
  31. buffer := bufio.NewReader(conn)
  32. conn.SetReadDeadline(time.Now().Add(timeout))
  33. n, err = buffer.Read(p)
  34. if err != nil {
  35. isTimeout = errTimeout(err)
  36. }
  37. return
  38. }
  39. // ReadBytes tcp reads until the first occurrence of delim in the input,
  40. // returning a slice containing the data up to and including the delimiter.
  41. // If ReadBytes encounters an error before finding a delimiter,
  42. // it returns the data read before the error and the error itself (often io.EOF).
  43. // ReadBytes returns err != nil if and only if the returned data does not end in
  44. // delim.
  45. // For simple uses, a Scanner may be more convenient.
  46. func ReadBytes(conn *net.TCPConn, timeout time.Duration, delim byte) (data []byte, isTimeout bool, err error) {
  47. buffer := bufio.NewReader(conn)
  48. conn.SetReadDeadline(time.Now().Add(timeout))
  49. data, err = buffer.ReadBytes(delim)
  50. if err != nil {
  51. isTimeout = errTimeout(err)
  52. }
  53. return
  54. }
  55. // Optimize TCP connect optimize
  56. func Optimize(conn *net.TCPConn) (err error) {
  57. err = conn.SetNoDelay(true)
  58. if err != nil {
  59. return
  60. }
  61. err = conn.SetKeepAlive(true)
  62. if err != nil {
  63. return
  64. }
  65. err = conn.SetKeepAlivePeriod(3 * time.Minute)
  66. return
  67. }