dtrnish3637 2019-09-02 05:36
浏览 54
已采纳

简单的服务器客户端通信不起作用

This seemingly simple example is not working as expected and I feel bad for asking but here goes:

There's a client that retries connecting to the server, sends a message, and then waits for a response:

func client() {
    var conn net.Conn
    var err error

    // retry server until it is up
    for {
        conn, err = net.Dial("tcp", ":8081")
        if err == nil {
            break
        }
        log.Println(err)
        time.Sleep(time.Second)
    }

    // write to server
    _, err = conn.Write([]byte("request"))
    if err != nil {
        log.Println(err)
        return
    }

    // block & read from server
    var buf []byte
    n, err := conn.Read(buf)
    if err != nil {
        log.Println(err)
        return
    }
    log.Printf("From server: %s
", buf[:n])
}

It connects to a server which for each connection, reads and interprets the sent data, and sends a response if needed:

func server() {
    ln, _ := net.Listen("tcp", ":8081")
    for {
        conn, _ := ln.Accept()
        go handleConn(conn)
    }
}

func handleConn(conn net.Conn) {
    var buf []byte
    n, err := conn.Read(buf)
    if err != nil {
        return
    }
    log.Printf("Server got: %s
", buf)

    if string(buf[:n]) == "request" {
        _, _ = conn.Write([]byte("response"))
    }
}

All driven by the main function:

func main() {
    go client()
    server()
}

Error handling is omitted for brevity. The expected behavior is that the client will connect to the server and send the message "request" and then block on the read. The server receives "request" and sends the message "response" back to the same connection. The client unblock, prints the received message and exits. Instead, when the program is run, the following is printed:

2019/09/01 22:24:02 From server: 
2019/09/01 22:24:02 Server got: 

Suggesting that no data was exchanged, and that the client did not block.

  • 写回答

1条回答

  • douyan2470 2019-09-02 06:22
    关注

    The looping in client is strange! The looping not make sense if read/write is out. But the error is only this:

      //var buf []byte <--- this read 0 bytes
      buf := make([]byte, 1024) 
      n, err := conn.Read(buf)
    

    A proposal for you:

    package main
    
    import (
        "log"
        "net"
        "time"
    )
    
    func client() {
        var conn net.Conn
        var err error
    
        // retry server until it is up
        for {
            log.Printf("Connecting...")
            conn, err = net.Dial("tcp", ":8082")
            if err != nil {
                log.Println(err)
                break
            }
            time.Sleep(time.Second)
            // write to server
            log.Printf("Writing...")
            _, err = conn.Write([]byte("request"))
            if err != nil {
                log.Println(err)
                return
            }
            // block & read from server
            log.Printf("Reading...")
            var buf []byte
            n, err := conn.Read(buf)
            if err != nil {
                log.Println(err)
                return
            }
            log.Printf("From server: %s
    ", buf[:n])
        }
    }
    
    func server() {
        ln, _ := net.Listen("tcp", ":8082")
        for {
            conn, _ := ln.Accept()
            go handleConn(conn)
        }
    }
    
    func handleConn(conn net.Conn) {
        buf := make([]byte, 1024)
        n, err := conn.Read(buf)
        if err != nil {
            return
        }
        log.Printf("Server got: [%d bytes] %s
    ", n, buf)
    
        if string(buf[:n]) == "request" {
            _, _ = conn.Write([]byte("response"))
        }
        conn.Close()
    }
    
    func main() {
        go client()
        server()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog