Unix domain sockets in Go - Golang News https://golangnews.org/2019/02/unix-domain-sockets-in-go/
package main
import ( "fmt" "log" "net" "os" "time" )
const SockAddr = "/tmp/echo.sock"
var reqCounter int64 var startTime time.Time
func init() { startTime = time.Now()
} func echoServer(c net.Conn) { reqCounter += 1 lastMilliseconds := time.Since(startTime) b1 := make([]byte, 128) n, err := c.Read(b1) fmt.Println("n, err", n, err, "b1", b1, "\nrcv\n", string(b1), "Client connected [%s]", c.RemoteAddr().Network()) c.Close() ns := 10000000000.0 lastSeconds := float64(lastMilliseconds) / ns fmt.Println("\nreqCounter=", reqCounter, "QPS=", float64(reqCounter)/lastSeconds) }
func main() {
if err := os.RemoveAll(SockAddr); err != nil { log.Fatal(err) }
l, err := net.Listen("unix", SockAddr) if err != nil { log.Fatal("listen error:", err) } defer l.Close()
for { // Accept new connections, dispatching them to echoServer // in a goroutine. conn, err := l.Accept() if err != nil { log.Fatal("accept error:", err) }
go echoServer(conn) } }
package main
import ( "fmt" "net" "time" )
const SockAddr = "/tmp/echo.sock"
func main() {
for { c, err := net.Dial("unix", SockAddr) if err != nil { fmt.Println("c,err", c, err) continue }
clientStr := "abc世界-1--" + time.Now().String() b1 := []byte(clientStr) n, err := c.Write(b1) fmt.Println(time.Now(), n, err, "clientStr\n", clientStr)
e := c.Close() fmt.Println("e", e)
} }
Go/src/net/unixsock.go:57
// ResolveUnixAddr returns an address of Unix domain socket end point.
//
// The network must be a Unix network name.
//
// See func Dial for a description of the network and address
// parameters.
func ResolveUnixAddr(network, address string) (*UnixAddr, error) {
switch network {
case "unix", "unixgram", "unixpacket":
return &UnixAddr{Name: address, Net: network}, nil
default:
return nil, UnknownNetworkError(network)
}
}
|
请发表评论