Home > Backend Development > Golang > Why Does My Go Unix Socket Echo Server Disconnect: A Unidirectional Communication Problem?

Why Does My Go Unix Socket Echo Server Disconnect: A Unidirectional Communication Problem?

DDD
Release: 2024-12-02 21:16:12
Original
161 people have browsed it

Why Does My Go Unix Socket Echo Server Disconnect: A Unidirectional Communication Problem?

Unidirectional Communication in Unix Sockets: Resolving the Echo Server Disconnect

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.

The Issue

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.

Corrected Client Code

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)
    }
}
Copy after login

Final Thoughts

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template