用net包来检测服务器端口是否被占用

    1. package main
    2. import (
    3. "fmt"
    4. "net"
    5. "time"
    6. )
    7. func main(){
    8. conn, err := net.DialTimeout("tcp", "127.0.0.1:8088", 3*time.Second)
    9. if err != nil {
    10. err = fmt.Errorf("端口未被占用")
    11. fmt.Println(err)
    12. return
    13. }
    14. defer conn.Close()
    15. fmt.Println("端口已被占用")
    16. }