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