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 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题