github.com/gogf/gf@v1.16.9/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/gogf/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.SetreceiveDeadline(time.Now().Add(timeout)); err != nil { 47 return nil, err 48 } 49 defer c.SetreceiveDeadline(time.Time{}) 50 data, err = c.RecvPkg(option...) 51 return 52 } 53 54 // SendPkgWithTimeout writes data to connection with timeout using simple package protocol. 55 func (c *PoolConn) SendPkgWithTimeout(data []byte, timeout time.Duration, option ...PkgOption) (err error) { 56 if err := c.SetSendDeadline(time.Now().Add(timeout)); err != nil { 57 return err 58 } 59 defer c.SetSendDeadline(time.Time{}) 60 err = c.SendPkg(data, option...) 61 return 62 } 63 64 // SendRecvPkg writes data to connection and blocks reading response using simple package protocol. 65 func (c *PoolConn) SendRecvPkg(data []byte, option ...PkgOption) ([]byte, error) { 66 if err := c.SendPkg(data, option...); err == nil { 67 return c.RecvPkg(option...) 68 } else { 69 return nil, err 70 } 71 } 72 73 // SendRecvPkgWithTimeout reads data from connection with timeout using simple package protocol. 74 func (c *PoolConn) SendRecvPkgWithTimeout(data []byte, timeout time.Duration, option ...PkgOption) ([]byte, error) { 75 if err := c.SendPkg(data, option...); err == nil { 76 return c.RecvPkgWithTimeout(timeout, option...) 77 } else { 78 return nil, err 79 } 80 }