0
我試圖寫Golang一個簡單的客戶端,但只要我運行它退出,Golang TCP客戶端退出
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中的其他代碼
的問題是,隨走,不等待運行的程序去完成。使用一個等待組。 – Kiril 2014-10-11 12:11:17
@Kiril嘗試使用WaitGroup仍然存在相同問題的建議 – 2014-10-11 13:40:23
如何?更新你的代碼。 – Kiril 2014-10-11 13:42:22