Golang TCP客户端退出

Golang TCP客户端退出,go,network-programming,client,Go,Network Programming,Client,我试图在Golang中编写一个简单的客户端,但一旦我运行它,它就会退出 package main import ( "fmt" "net" "os" "bufio" "sync" ) func main() { conn, err := net.Dial("tcp", "localhost:8081") if err != nil {

我试图在Golang中编写一个简单的客户端,但一旦我运行它,它就会退出

package main

    import (
        "fmt"
        "net"
        "os"
        "bufio"
        "sync"
    )

    func main() {

        conn, err := net.Dial("tcp", "localhost:8081")
        if err != nil {
            fmt.Println(err);
            conn.Close();
        }
        fmt.Println("Got connection, type anything...new line sends and quit quits the session");
        go sendRequest(conn)
    }


    func sendRequest(conn net.Conn) {

        reader := bufio.NewReader(os.Stdin)
        var wg sync.WaitGroup
        for {
            buff := make([]byte, 2048);
            line, err := reader.ReadString('\n')
            wg.Add(1);
            if err != nil {
                fmt.Println("Error while reading string from stdin",err)
                conn.Close()
                break;
            }

            copy(buff[:], line)
            nr, err := conn.Write(buff)
            if err != nil {
                fmt.Println("Error while writing from client to connection", err);
                break;
            }
            fmt.Println(" Wrote : ", nr);
            wg.Done()
            buff = buff[:0]
        }
        wg.Wait()

    }
当尝试运行它时,我得到以下输出

Got connection, type anything...new line sends and quit quits the session

Process finished with exit code 0

我希望代码会使stdin(终端)打开并等待输入文本,但它会立即退出。我是否应该将代码替换为从stdin读取的其他代码

main
函数返回时,Go程序退出

简单的解决方法是直接调用
sendRequest
。此程序中不需要goroutine

func main() {

  conn, err := net.Dial("tcp", "localhost:8081")
  if err != nil {
    fmt.Println(err);
    conn.Close();
  }
  fmt.Println("Got connection, type anything...new line sends and quit quits the session");
  sendRequest(conn) // <-- go removed from this line.
}

问题是go并不等待运行go例程完成。使用waitgroup。检查如何等待所有Goroutine完成的答案:@Kiril尝试了您的建议,使用waitgroup仍然存在相同的问题how?更新你的代码。
func main() {
  conn, err := net.Dial("tcp", "localhost:8081")
  if err != nil {
    fmt.Println(err);
    conn.Close();
  }
  var wg sync.WaitGroup
  fmt.Println("Got connection, type anything...new line sends and quit quits the session");
  wg.Add(1)
  go sendRequest(&wg, conn)
  wg.Wait()
}

func sendRequest(wg *sync.WaitGroup, conn net.Conn) {
  defer wg.Done()
  // same code as before
}