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