猿问

Golang TCP 客户端退出

我正在尝试在 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(terminal) 打开并等待输入文本,但它会立即退出。我是否应该用其他东西替换代码以从标准输入读取


绝地无双
浏览 237回答 1
1回答

江户川乱折腾

当main函数返回时,Go 程序退出。简单的解决方法是sendRequest直接调用。这个程序不需要goroutine。func main() {&nbsp; conn, err := net.Dial("tcp", "localhost:8081")&nbsp; if err != nil {&nbsp; &nbsp; fmt.Println(err);&nbsp; &nbsp; conn.Close();&nbsp; }&nbsp; fmt.Println("Got connection, type anything...new line sends and quit quits the session");&nbsp; sendRequest(conn) // <-- go removed from this line.}如果需要够程,然后用sync.WaitGroup使main等待够程来完成:func main() {&nbsp; conn, err := net.Dial("tcp", "localhost:8081")&nbsp; if err != nil {&nbsp; &nbsp; fmt.Println(err);&nbsp; &nbsp; conn.Close();&nbsp; }&nbsp; var wg sync.WaitGroup&nbsp; fmt.Println("Got connection, type anything...new line sends and quit quits the session");&nbsp; wg.Add(1)&nbsp; go sendRequest(&wg, conn)&nbsp; wg.Wait()}func sendRequest(wg *sync.WaitGroup, conn net.Conn) {&nbsp; defer wg.Done()&nbsp; // same code as before}
随时随地看视频慕课网APP

相关分类

Go
我要回答