先給出結(jié)論:
同一個進程,使用一個端口,然后連接關(guān)閉,大約需要30s后才可再次使用這個端口。
測試
首先使用端口9001連接服務(wù)端,發(fā)送數(shù)據(jù),然后關(guān)閉連接,接著再次使用端口9001連接服務(wù)端,如果連接失敗,間隔15s后,再次嘗試,最多嘗試3次,。
client
package main
import (
"bufio"
"fmt"
"net"
"os"
"time"
)
func DialCustom(network, address string, timeout time.Duration, localIP []byte, localPort int)(net.Conn,error) {
netAddr := net.TCPAddr{Port:localPort}
if len(localIP) != 0 {
netAddr.IP = localIP
}
fmt.Println("netAddr:", netAddr)
d := net.Dialer{Timeout: timeout, LocalAddr: netAddr}
return d.Dial(network, address)
}
func getOneConn() {
serverAddr := "127.0.0.1:8080"
// 172.28.172.180
//localIP := []byte{0xAC, 0x1C, 0xAC, 0xB4} // IP
localIP := []byte{} // any IP
localPort := 9001
var conn net.Conn
var err error
for i:=0;i3;i++{
conn, err = DialCustom("tcp", serverAddr, time.Second*10, localIP,localPort)
if err != nil {
fmt.Println("dial failed:", err)
if i == 2 {
os.Exit(1)
}
time.Sleep(15*time.Second)
} else {
break
}
}
defer conn.Close()
buffer := make([]byte, 512)
reader := bufio.NewReader(conn)
n, err2 := reader.Read(buffer)
if err2 != nil {
fmt.Println("Read failed:", err2)
return
}
fmt.Println("count:", n, "msg:", string(buffer))
}
func main() {
getOneConn()
fmt.Println("=========================")
getOneConn()
fmt.Println("=========================")
select{}
}
server
package main
import (
"fmt"
"net"
"log"
)
func main() {
addr := "0.0.0.0:8080"
tcpAddr, err := net.ResolveTCPAddr("tcp",addr)
if err != nil {
log.Fatalf("net.ResovleTCPAddr fail:%s", addr)
}
listener, err := net.ListenTCP("tcp", tcpAddr)
if err != nil {
log.Fatalf("listen %s fail: %s", addr, err)
} else {
log.Println("rpc listening", addr)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Println("listener.Accept error:", err)
continue
}
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
//defer conn.Close()
var buffer []byte = []byte("You are welcome. I'm server.")
n, err := conn.Write(buffer)
if err != nil {
fmt.Println("Write error:", err)
}
fmt.Println("send:", n)
fmt.Println("connetion end")
}
output
client輸出:
$ ./client
netAddr: :9001
count: 28 msg: You are welcome. I'm server.
=========================
netAddr: :9001
dial failed: dial tcp :9001->127.0.0.1:8080: bind: address already in use
netAddr: :9001
dial failed: dial tcp :9001->127.0.0.1:8080: bind: address already in use
netAddr: :9001
count: 28 msg: You are welcome. I'm server.
=========================
經(jīng)過3次重試,30s后,才可以重新使用同一個端口9001進行連接。也就是同一個進程的情況狂下,一個連接關(guān)閉后,端口大約30s后才可以被使用。
到此這篇關(guān)于Golang 端口復(fù)用測試的實現(xiàn)的文章就介紹到這了,更多相關(guān)Golang 端口復(fù)用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- golang端口占用檢測的使用
- GO語言實現(xiàn)的端口掃描器分享