【发布时间】:2017-11-05 00:30:24
【问题描述】:
所以我开始了一个项目,其中涉及模块通过 websockets 从服务器发送和接收消息。但是,我想要一种简单的方式来与模块交互并向模块发送消息。
所以我让程序在 goroutine 中询问我的消息,当我按 Enter 时,它会发送消息并提示我输入另一个消息。在主 goroutine 中,它会一直等到它收到一条消息,当它收到一条消息时,覆盖当前行并将之前行中的内容替换为新行。
然而,只有一个问题。它不知道如何将我的输入放在新行上。在我对以下示例的测试中,似乎 os.Stdin.Read 停止,直到它收到换行符。
package main
import (
"bufio"
"fmt"
"os"
"time"
)
func main() {
// Input Buffer
var msg string
scanner := bufio.NewScanner(os.Stdin)
scanner.Split(bufio.ScanBytes)
go func() {
for {
// Prompt the user for a message
fmt.Print("client1: ")
// Scan os.Stdin, splitting on bytes
for scanner.Scan() {
if scanner.Text() == "\n" {
break
} else {
// If the character is not \n, add to the input buffer
msg += scanner.Text()
}
}
// Do something with the input buffer then clear it
fmt.Println(msg)
msg = ""
}
}()
for {
select {
// Receive a message from a client
case <-time.After(5 * time.Second):
// Write the message over the current line
fmt.Println("\rclient2: Hello")
// Prompt the user again for their message
// proving the current input buffer
fmt.Print("client1: " + msg)
}
}
}
示例输出:
client1: Hello!
Hello!
client2: Hello
client1: Bye!
Bye!
client2: Hello
client2: Hello // Was "client1: Good " before being overwritten
client1: Bye!
Good Bye!
非常感谢任何想法。提前谢谢你。
【问题讨论】: