gpt4 book ai didi

go - 简单消息客户端 golang

转载 作者:IT王子 更新时间:2023-10-29 01:47:28 26 4
gpt4 key购买 nike

所以我开始了一个项目,该项目涉及通过 websockets 从服务器发送和接收消息的模块。但是,我想要一种简单的方式来与模块交互并向模块发送消息。

所以我让程序在 goroutine 中询问我的消息,当我按下回车键时,它会发送消息并提示我输入另一条消息。在主 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!

非常感谢任何想法。先谢谢你。

最佳答案

这似乎是 IO 竞争条件。您的 goroutine 未与 main 同步。顺便说一句,ScanLines 会为您做同样的事情。考虑一下:

package main

import (
"bufio"
"fmt"
"os"
)

func main() {
scanner := bufio.NewScanner(os.Stdin)
msgQ := make(chan string)

defer close(msgQ)

go func() {
for {
// Prompt the user for a message
fmt.Print("client1: ")
msg, ok := <-msgQ
if !ok {
return
}
fmt.Println("\rclient1 said: " + msg)
// Write the message over the current line
fmt.Println("client2: Hello")
}
}()


// Scan os.Stdin, splitting on bytes
for scanner.Scan() {
msgQ <- scanner.Text()
}

}

编辑:根据评论,此代码显示了该想法的错误之处。当你写东西但不按 ENTER 键时,client2 会覆盖当前行。你可以保存(CTRL-U)和恢复(CTRL-Y)当前行,但我没有找到 ANSI 签名或 Signal 以编程方式调用它。

package main

import (
"bufio"
"fmt"
"os"
"time"
)

func main() {

scanner := bufio.NewScanner(os.Stdin)
sendQ := make(chan struct{})

defer close(sendQ)

//simulate local client1 console
go func() {
for {
fmt.Print("client1: ")
select {
case _, ok := <-sendQ:
if !ok {
return
}
case <-time.After(5 * time.Second):
fmt.Printf("\r\033[K") // delete current line from right
fmt.Println("client2: Hello")
}
}
}()

for scanner.Scan() {
sendQ <- struct{}{}
}

}

关于go - 简单消息客户端 golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44348513/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com