The gtcp module also provides some common utility methods.

    Usage:

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

    API Documentation:

    https://pkg.go.dev/github.com/gogf/gf/v2/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 is used to simplify the creation of the standard library connection object net.Conn;
    2. NewNetConnTLS and NewNetConnKeyCrt are used to create TCP clients that support TLS secure encrypted communication;
    3. The Send* series of methods send data directly through the given address and obtain the returned results of the request, which are used for short connection requests;

    Below is a simple example where we use utility methods to access the specified web site:

    1. package main
    2. import (
    3. "fmt"
    4. "github.com/gogf/gf/v2/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. }

    In this example, we access the Baidu homepage via TCP, simulate the HTTP request header information, and receive the return result. After execution, the output result is as follows:

    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