Golang TCP客户端退出

时间:2014-10-11 11:43:33

标签: 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 {
            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中读取

1 个答案:

答案 0 :(得分: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.WaitGroupmain等待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
}
相关问题