gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/ipc/socket/unix-client/main.go (about) 1 package main 2 3 import ( 4 "errors" 5 "fmt" 6 "gitee.com/sy_183/go-common/slice/unsafe" 7 "io" 8 "net" 9 "os" 10 "os/signal" 11 "syscall" 12 "time" 13 ) 14 15 func run() (code int) { 16 addr := &net.UnixAddr{Name: "/run/server.sock", Net: "unixpacket"} 17 conn, err := net.DialUnix("unixpacket", nil, addr) 18 if err != nil { 19 fmt.Fprintf(os.Stderr, "ERROR: dial unix connection to '%s' failed: %s\n", addr, err) 20 return 1 21 } 22 fmt.Printf("INFO: dail unix connection to '%s' success\n", addr) 23 24 sc := make(chan os.Signal, 1) 25 signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM) 26 timer := time.NewTimer(time.Second) 27 interrupter := make(chan struct{}, 1) 28 29 go func() { 30 <-sc 31 interrupter <- struct{}{} 32 if err := conn.Close(); err != nil { 33 fmt.Fprintf(os.Stderr, "ERROR: close unix connection failed: %s\n", err) 34 code = 1 35 } 36 }() 37 38 buf := make([]byte, 0, 4096) 39 for i := 0; ; i++ { 40 data := fmt.Appendf(buf, "data %d", i) 41 n, err := conn.Write(data) 42 if err != nil { 43 if errors.Is(err, net.ErrClosed) || err == io.EOF { 44 return 45 } 46 fmt.Fprintf(os.Stderr, "ERROR: write unix connection to '%s' failed: %s\n", addr, err) 47 return 1 48 } 49 fmt.Printf("INFO: write %d bytes to %s: %s\n", n, addr.Name, unsafe.String(data[:n])) 50 select { 51 case <-timer.C: 52 timer.Reset(time.Second) 53 case <-interrupter: 54 return 55 } 56 } 57 } 58 59 func main() { 60 os.Exit(run()) 61 }