GoFrame TCP組件-工具方法

2022-04-15 13:50 更新

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

使用方式:

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

接口文檔:

https://pkg.go.dev/github.com/gogf/gf/v2/net/gtcp

func LoadKeyCrt(crtFile, keyFile string) (*tls.Config, error)
func NewNetConn(addr string, timeout ...int) (net.Conn, error)
func NewNetConnKeyCrt(addr, crtFile, keyFile string) (net.Conn, error)
func NewNetConnTLS(addr string, tlsConfig *tls.Config) (net.Conn, error)
func Send(addr string, data []byte, retry ...Retry) error
func SendPkg(addr string, data []byte, option ...PkgOption) error
func SendPkgWithTimeout(addr string, data []byte, timeout time.Duration, option ...PkgOption) error
func SendRecv(addr string, data []byte, receive int, retry ...Retry) ([]byte, error)
func SendRecvPkg(addr string, data []byte, option ...PkgOption) ([]byte, error)
func SendRecvPkgWithTimeout(addr string, data []byte, timeout time.Duration, option ...PkgOption) ([]byte, error)
func SendRecvWithTimeout(addr string, data []byte, receive int, timeout time.Duration, retry ...Retry) ([]byte, error)
func SendWithTimeout(addr string, data []byte, timeout time.Duration, retry ...Retry) error

  1. ?NewNetConn?用于簡化標(biāo)準(zhǔn)庫連接對象?net.Conn?的創(chuàng)建;
  2. ?NewNetConnTLS?和?NewNetConnKeyCrt?用于創(chuàng)建支持?TLS?安全加密通信的?TCP?客戶端;
  3. ?Send*?系列方法直接通過給定地址進行數(shù)據(jù)發(fā)送,并獲取該請求的返回結(jié)果,用于短鏈接請求的情況;

以下為一個簡單的示例,我們使用工具方法來訪問指定的Web站點:

package main

import (
    "fmt"
    "github.com/gogf/gf/v2/net/gtcp"
)

func main() {
    data, err := gtcp.SendRecv("www.baidu.com:80", []byte("HEAD / HTTP/1.1\n\n"), -1)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(data))
}

在這個示例中,我們通過TCP訪問百度首頁,模擬HTTP請求頭信息,并獲得返回結(jié)果。 執(zhí)行后,輸出結(jié)果如下:

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


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號