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

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

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()
    }
    
    点赞 评论

相关推荐 更多相似问题