服务器无法在“Hello World”套接字程序中获取消息

时间:2014-02-16 11:32:52

标签: sockets unix go

我正在练习将unix socket与bufio一起使用。这是该计划:

    // Register server socket
    os.Remove("serversock")
    socket, err := net.ListenUnix("unix", &net.UnixAddr{"serversock", "unix"})
    if err != nil {
        panic(err)
    }
    go func() {
        for {
            // Accept new connection
            conn, err := socket.Accept()
            if err != nil {
                panic(err)
            }
            fmt.Println("Got connection")
            reader := bufio.NewReader(conn)
            line, err := reader.ReadString(byte('\n'))
            if err != nil {
                panic(err)
            }
            fmt.Println("Got line", line)
        }
    }()
    // Client connection
    conn, err := net.DialUnix("unix", nil, &net.UnixAddr{"serversock", "unix"})
    writer := bufio.NewWriter(conn)
    n, err := writer.WriteString("hello world\n")
    if err != nil {
        panic(err)
    }
    fmt.Println("Written", n)
    // Client wait
    time.Sleep(1 * time.Second)

运行时会打印:

Written 13
Got connection

然后存在,所以服务器似乎没有收到消息。我做错了什么?

1 个答案:

答案 0 :(得分:1)

您的编写器已缓冲,当您WriteString()时,它不会刷新缓冲区。只需致电writer.Flush()即可实际发送该行。您也可以尝试直接写入套接字,看看会发生什么。

此外,您的接受循环应如下所示:

go func() {
    for {
        // Accept new connection
        conn, err := socket.Accept()
        if err != nil {
            panic(err)
        }
        fmt.Println("Got connection")
        reader := bufio.NewReader(conn)

        //spawn a goroutine that has a read loop
        go func(reader *bufio.Reader) {
           for {
             line, err := reader.ReadString(byte('\n'))
             if err != nil {
                panic(err)
             }
             fmt.Println("Got line", line)
           }
        }(reader)
    }
}()