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

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个回答

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()
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐