123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- package tcp
- import (
- "bufio"
- "net"
- "time"
- )
- func errTimeout(err error) bool {
- if opErr, ok := err.(*net.OpError); ok {
- if opErr.Temporary() || opErr.Timeout() {
- return true
- }
- }
- return false
- }
- func Write(conn *net.TCPConn, timeout time.Duration, data []byte) (n int, isTimeout bool, err error) {
- conn.SetWriteDeadline(time.Now().Add(timeout))
- n, err = conn.Write(data)
- if err != nil {
- isTimeout = errTimeout(err)
- }
- return
- }
- func Read(conn *net.TCPConn, timeout time.Duration, p []byte) (n int, isTimeout bool, err error) {
- buffer := bufio.NewReader(conn)
- conn.SetReadDeadline(time.Now().Add(timeout))
- n, err = buffer.Read(p)
- if err != nil {
- isTimeout = errTimeout(err)
- }
- return
- }
- func ReadBytes(conn *net.TCPConn, timeout time.Duration, delim byte) (data []byte, isTimeout bool, err error) {
- buffer := bufio.NewReader(conn)
- conn.SetReadDeadline(time.Now().Add(timeout))
- data, err = buffer.ReadBytes(delim)
- if err != nil {
- isTimeout = errTimeout(err)
- }
- return
- }
- func Optimize(conn *net.TCPConn) (err error) {
- err = conn.SetNoDelay(true)
- if err != nil {
- return
- }
- err = conn.SetKeepAlive(true)
- if err != nil {
- return
- }
- err = conn.SetKeepAlivePeriod(3 * time.Minute)
- return
- }
|