SoFunction
Updated on 2025-03-04

Implementation of Golang port multiplexing test

Let's give a conclusion first:

For the same process, use a port, and then the connection is closed. It takes about 30 seconds before you can use this port again.

test

First, use port 9001 to connect to the server, send data, then close the connection, and then use port 9001 to connect to the server again. If the connection fails, try again after 15 seconds, try at most 3 times.

client

package main
import (

 "bufio"
 "fmt"
 "net"
 "os"
 "time"
)

func DialCustom(network, address string, timeout , localIP []byte, localPort int)(,error) {
 netAddr := &{Port:localPort}

 if len(localIP) != 0 {
  = localIP
 }

 ("netAddr:", netAddr)

 d := {Timeout: timeout, LocalAddr: netAddr}
 return (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 
 var err error

 for i:=0;i<3;i++{

 conn, err = DialCustom("tcp", serverAddr, *10, localIP,localPort)
 if err != nil {
 ("dial failed:", err)
 if i == 2 {
 (1)
 }
 (15*)
 } else {
 break
 }
 }

 defer ()


 buffer := make([]byte, 512)
 reader := (conn)

 n, err2 := (buffer)
 if err2 != nil {
 ("Read failed:", err2)
 return
 }

 ("count:", n, "msg:", string(buffer))

}


func main() {
 getOneConn()
 ("=========================")
 getOneConn()
 ("=========================")
 select{}

}

server

package main

import (
 "fmt"
 "net"
 "log"
)

func main() {

 addr := "0.0.0.0:8080"

 tcpAddr, err := ("tcp",addr)

 if err != nil {
 (" fail:%s", addr)
 }

 listener, err := ("tcp", tcpAddr)
 if err != nil {
 ("listen %s fail: %s", addr, err)
 } else {
 
 ("rpc listening", addr)
 }


 for {
 conn, err := ()
 if err != nil {
 (" error:", err)
 continue
 }
 
 go handleConnection(conn)
 
 }

}


func handleConnection(conn ) {

 //defer ()

 var buffer []byte = []byte("You are welcome. I'm server.")

 n, err := (buffer)

 if err != nil {
 
 ("Write error:", err)
 }
 ("send:", n)

 ("connetion end")
}

output

Client output:

$ ./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.
=========================

After 3 retry, you can only use the same port 9001 to connect again after 30 seconds. In other words, in the case of the same process, a connection is closed and the port can only be used after about 30 seconds.

This is the end of this article about the implementation of Golang port reuse testing. For more related Golang port reuse content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!