syscall.Socket
package main
import (
"fmt"
"syscall"
)
func main() {
fd1, err := syscall.Socket(
syscall.AF_INET, syscall.SOCK_STREAM, syscall.IPPROTO_TCP)
if err != nil {
fmt.Printf("socket error: %v\n", err)
return
}
defer syscall.Close(fd1)
fmt.Printf("The file descriptor of socket: %d\n", fd1)
}
net.Dial
package main
import (
"fmt"
"bufio"
"io"
"net"
"runtime"
)
func main() {
network := "tcp"
host := "baidu.com"
reqStrTpl := `HEAD / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: %s
User-Agent: Dialer/%s
`
network1 := network + "4"
address1 := host + ":80"
fmt.Printf("Dial %q with network %q ...\n", address1, network1)
// 调用 syscall.Socket
conn1, err := net.Dial(network1, address1)
if err != nil {
fmt.Printf("dial error: %v\n", err)
return
}
defer conn1.Close()
reqStr1 := fmt.Sprintf(reqStrTpl, host, runtime.Version())
fmt.Printf("The request:\n%s\n", reqStr1)
_, err = io.WriteString(conn1, reqStr1)
if err != nil {
fmt.Printf("write error: %v\n", err)
return
}
fmt.Println()
reader1 := bufio.NewReader(conn1)
line1, err := reader1.ReadString('\n')
if err != nil {
fmt.Printf("read error: %v\n", err)
return
}
fmt.Printf("The first line of response:\n%s\n", line1)
fmt.Println()
}
net.DialTimeout 给定的超时时间
代表函数为网络连接建立完成而等待的最长时间,由参数 timeout 给定。
时间主要花费在“解析参数 network 和 address 值”和“创建 socket 实例并建立网络连接”上。
只要在绝对的超时时间到达,网络连接还没有建立完成,函数就会返回一个代表了 I/O 操作超时的错误值。
package main
import (
"fmt"
"net"
"time"
)
type dailArgs struct {
network string
address string
timeout time.Duration
}
func main() {
dialArgsList := []dailArgs {
{
"tcp",
"baidu.com:80",
time.Millisecond * 500,
},
{
"tcp",
"baidu.com:80",
time.Millisecond,
},
}
for _, args := range dialArgsList {
fmt.Printf("Dial %q with network %q and timeout %s ...\n",
args.address, args.network, args.timeout)
ts1 := time.Now()
conn, err := net.DialTimeout(args.network, args.address, args.timeout)
ts2 := time.Now()
fmt.Printf("Elapsed time: %s\n", time.Duration(ts2.Sub(ts1)))
if err != nil {
fmt.Printf("dial error: %v\n\n", err)
continue
}
defer conn.Close()
fmt.Printf("The local address: %s\n", conn.LocalAddr())
fmt.Printf("The remote address: %s\n", conn.RemoteAddr())
fmt.Println()
}
}