【问题标题】:Golang TCP client exitsGolang TCP 客户端退出
【发布时间】:2014-12-06 11:58:39
【问题描述】:

我正在尝试用 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

我期望代码会使标准输入(终端)打开并等待输入文本,但它会立即退出。我应该用其他东西替换代码以从标准输入读取

【问题讨论】:

  • 问题是 go 不等待运行 goroutines 完成。使用等待组。
  • 查看这个关于如何等待所有 goroutine 完成的答案:stackoverflow.com/questions/18207772/…
  • @Kiril 尝试了使用 WaitGroup 的建议,但仍然存在同样的问题
  • 怎么样?更新您的代码。

标签: go network-programming client


【解决方案1】:

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.
}

如果需要 goroutine,则使用 sync.WaitGroup 使 main 等待 goroutine 完成:

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
}

【讨论】:

    猜你喜欢
    • 2014-06-02
    • 2017-09-23
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多