github.com/wangyougui/gf/v2@v2.6.5/net/gtcp/gtcp_pool_pkg.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/wangyougui/gf. 6 7 package gtcp 8 9 import ( 10 "time" 11 ) 12 13 // SendPkg sends a package containing `data` to the connection. 14 // The optional parameter `option` specifies the package options for sending. 15 func (c *PoolConn) SendPkg(data []byte, option ...PkgOption) (err error) { 16 if err = c.Conn.SendPkg(data, option...); err != nil && c.status == connStatusUnknown { 17 if v, e := c.pool.NewFunc(); e == nil { 18 c.Conn = v.(*PoolConn).Conn 19 err = c.Conn.SendPkg(data, option...) 20 } else { 21 err = e 22 } 23 } 24 if err != nil { 25 c.status = connStatusError 26 } else { 27 c.status = connStatusActive 28 } 29 return err 30 } 31 32 // RecvPkg receives package from connection using simple package protocol. 33 // The optional parameter `option` specifies the package options for receiving. 34 func (c *PoolConn) RecvPkg(option ...PkgOption) ([]byte, error) { 35 data, err := c.Conn.RecvPkg(option...) 36 if err != nil { 37 c.status = connStatusError 38 } else { 39 c.status = connStatusActive 40 } 41 return data, err 42 } 43 44 // RecvPkgWithTimeout reads data from connection with timeout using simple package protocol. 45 func (c *PoolConn) RecvPkgWithTimeout(timeout time.Duration, option ...PkgOption) (data []byte, err error) { 46 if err := c.SetDeadlineRecv(time.Now().Add(timeout)); err != nil { 47 return nil, err 48 } 49 defer func() { 50 _ = c.SetDeadlineRecv(time.Time{}) 51 }() 52 data, err = c.RecvPkg(option...) 53 return 54 } 55 56 // SendPkgWithTimeout writes data to connection with timeout using simple package protocol. 57 func (c *PoolConn) SendPkgWithTimeout(data []byte, timeout time.Duration, option ...PkgOption) (err error) { 58 if err := c.SetDeadlineSend(time.Now().Add(timeout)); err != nil { 59 return err 60 } 61 defer func() { 62 _ = c.SetDeadlineSend(time.Time{}) 63 }() 64 err = c.SendPkg(data, option...) 65 return 66 } 67 68 // SendRecvPkg writes data to connection and blocks reading response using simple package protocol. 69 func (c *PoolConn) SendRecvPkg(data []byte, option ...PkgOption) ([]byte, error) { 70 if err := c.SendPkg(data, option...); err == nil { 71 return c.RecvPkg(option...) 72 } else { 73 return nil, err 74 } 75 } 76 77 // SendRecvPkgWithTimeout reads data from connection with timeout using simple package protocol. 78 func (c *PoolConn) SendRecvPkgWithTimeout(data []byte, timeout time.Duration, option ...PkgOption) ([]byte, error) { 79 if err := c.SendPkg(data, option...); err == nil { 80 return c.RecvPkgWithTimeout(timeout, option...) 81 } else { 82 return nil, err 83 } 84 }