
在 go 中同时监听客户端连接和用户命令输入
在编写终端聊天程序时,服务端需要同时监听客户端连接和用户在终端输入的命令。这是因为服务端既需要处理客户端的请求,又需要及时响应用户的输入。
为了实现这一功能,可以利用 go 的并发机制。具体的做法是,为客户端连接和用户命令输入分别创建两个 goroutine。
- 客户端连接 goroutine:该 goroutine监听服务端 socket,等待客户端连接。一旦有客户端连接,该 goroutine 就会接收客户端发送的消息,并对消息进行处理。
- 用户命令输入 goroutine:该 goroutine 从终端读取用户输入的命令。当用户输入命令后,该 goroutine 会将命令发送到服务端的另一端。
这两个 goroutine 可以通过信道进行通信,这样可以确保消息在两个 goroutine 之间同步。
优化代码:
- 将信道的声明移动到主函数中,以便在其他函数中直接使用它们。
- 使用无限循环来不断地从信道中接收消息,从而避免 goroutine 在没有消息时处于阻塞状态。
优化后的代码如下:
package main
import (
"fmt"
"os"
)
var recvFromTerminalChan = make(chan string)
var recvFromNetChan = make(chan string)
func main() {
go readFromTerminal()
for {
select {
case str := zuojiankuohaophpcn-recvFromTerminalChan:
go sendCommandToNet(str)
case str := zuojiankuohaophpcn-recvFromNetChan:
go doContentFromNet(str)
}
}
}
func readFromTerminal() {
var input string
for {
fmt.Scan(&input)
fmt.Println("input content : ", input)
recvFromTerminalChan zuojiankuohaophpcn- input
}
}
func sendCommandToNet(command string) {
fmt.Println("command : ", command)
if command == "quit" {
close(recvFromTerminalChan)
close(recvFromNetChan)
os.Exit(0)
}
content := command
recvFromNetChan zuojiankuohaophpcn- content
}
func doContentFromNet(content string) {
fmt.Println("content from net : ", content)
}










