Bidirectional Unix Socket Communication in Go
Unix sockets provide a convenient mechanism for implementing inter-process communication within a system. In Go, networking operations can be performed using the net package. Occasionally, when attempting to establish bidirectional communication using Unix sockets, it may appear that only one direction is functioning.
One possible cause for this behavior is insufficient error handling. In the given example, the server's write operation lacked error handling, leading to potential data loss. By adding a panic when an error occurs during the write operation, we ensure that any data loss is immediately apparent.
Additionally, within the client's goroutine, the absence of error handling for the read operation prevented the client from receiving any data sent by the server. Including error handling and adding a call to a separate reader goroutine to handle incoming data from the server resolves this issue.
Here is a modified version of the example with the necessary error handling adjustments:
package main import ( "log" "net" ) func echoServer(c net.Conn) { for { buf := make([]byte, 512) nr, err := c.Read(buf) if err != nil { return } data := buf[0:nr] println("Server got:", string(data)) _, err = c.Write(data) if err != nil { log.Fatal("Write: ", err) } } } func main() { l, err := net.Listen("unix", "/tmp/echo.sock") if err != nil { log.Fatal("listen error:", err) } for { fd, err := l.Accept() if err != nil { log.Fatal("accept error:", err) } go echoServer(fd) } }
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) } }
With these modifications in place, bidirectional communication between the client and server is established, allowing for both sending and receiving of data through the Unix socket.
The above is the detailed content of Why is My Go Unix Socket Only Communicating One Way?. For more information, please follow other related articles on the PHP Chinese website!