Home >Backend Development >Golang >Why Does My Go Unix Socket Echo Server Disconnect: A Unidirectional Communication Problem?
In Go, Unix sockets provide a mechanism for inter-process communication. However, a common issue arises when attempting to establish a bidirectional connection, resulting in the server receiving but not responding to client messages.
A closer look reveals a missing piece in the example client code. While it transmits data to the server, it does not read the server's response. Adding code to address this resolves the issue.
The corrected client code includes a goroutine that reads data from the server. Additionally, the use of defer and break ensures proper cleanup and exit of the goroutine.
package main import ( "io" "log" "net" "time" ) func reader(r io.Reader) { buf := make([]byte, 1024) for { n, err := r.Read(buf[:]) if err != nil { return } println("Client got:", string(buf[0:n])) } } func main() { c, err := net.Dial("unix", "/tmp/echo.sock") if err != nil { panic(err) } defer c.Close() go reader(c) for { _, err := c.Write([]byte("hi")) if err != nil { log.Fatal("write error:", err) break } time.Sleep(1e9) } }
By implementing the missing read functionality in the client code, bidirectional communication is established, allowing the client to receive and respond to the server's messages. This approach ensures a fully functional echo server and client.
The above is the detailed content of Why Does My Go Unix Socket Echo Server Disconnect: A Unidirectional Communication Problem?. For more information, please follow other related articles on the PHP Chinese website!