gtcp模块也提供了一些常用的工具方法。

    使用方式

    1. import "github.com/gogf/gf/net/gtcp"

    接口文档

    https://godoc.org/github.com/gogf/gf/net/gtcp

    1. func LoadKeyCrt(crtFile, keyFile string) (*tls.Config, error)
    2. func NewNetConn(addr string, timeout ...int) (net.Conn, error)
    3. func NewNetConnKeyCrt(addr, crtFile, keyFile string) (net.Conn, error)
    4. func NewNetConnTLS(addr string, tlsConfig *tls.Config) (net.Conn, error)
    5. func Send(addr string, data []byte, retry ...Retry) error
    6. func SendPkg(addr string, data []byte, option ...PkgOption) error
    7. func SendPkgWithTimeout(addr string, data []byte, timeout time.Duration, option ...PkgOption) error
    8. func SendRecv(addr string, data []byte, receive int, retry ...Retry) ([]byte, error)
    9. func SendRecvPkg(addr string, data []byte, option ...PkgOption) ([]byte, error)
    10. func SendRecvPkgWithTimeout(addr string, data []byte, timeout time.Duration, option ...PkgOption) ([]byte, error)
    11. func SendRecvWithTimeout(addr string, data []byte, receive int, timeout time.Duration, retry ...Retry) ([]byte, error)
    12. func SendWithTimeout(addr string, data []byte, timeout time.Duration, retry ...Retry) error
    1. NewNetConn用于简化标准库连接对象net.Conn的创建;
    2. NewNetConnTLSNewNetConnKeyCrt用于创建支持TLS安全加密通信的TCP客户端;
    3. Send*系列方法直接通过给定地址进行数据发送,并获取该请求的返回结果,用于短链接请求的情况;

    以下为一个简单的示例,我们使用工具方法来访问指定的Web站点:

    1. package main
    2. import (
    3. "fmt"
    4. "github.com/gogf/gf/net/gtcp"
    5. )
    6. func main() {
    7. data, err := gtcp.SendRecv("www.baidu.com:80", []byte("HEAD / HTTP/1.1\n\n"), -1)
    8. if err != nil {
    9. panic(err)
    10. }
    11. fmt.Println(string(data))
    12. }

    在这个示例中,我们通过TCP访问百度首页,模拟HTTP请求头信息,并获得返回结果。执行后,输出结果如下:

    1. HTTP/1.1 302 Found
    2. Connection: Keep-Alive
    3. Content-Length: 17931
    4. Content-Type: text/html
    5. Date: Tue, 04 Jun 2019 15:53:09 GMT
    6. Etag: "54d9749e-460b"
    7. Server: bfe/1.0.8.18