我正在尝试通过检查golang TCPConn.Write返回的错误来检测发送失败,但它为nil。我也尝试使用TCPConn.SetWriteDeadline,但没有成功。事情就是这样发生的:服务器启动客户端连接服务器发送一条消息,客户端收到它客户端关闭服务器再发送一条消息:没有错误服务器发送第三条消息:仅现在出现错误问题:为什么仅向不存在的客户端发送第二条消息会导致错误?案件应如何妥善处理?代码如下:package mainimport ( "net" "os" "bufio" "fmt" "time")func AcceptConnections(listener net.Listener, console <- chan string) { msg := "" for { conn, err := listener.Accept() if err != nil { panic(err) } fmt.Printf("client connected\n") for { if msg == "" { msg = <- console fmt.Printf("read from console: %s", msg) } err = conn.SetWriteDeadline(time.Now().Add(time.Second)) if err != nil { fmt.Printf("SetWriteDeadline failed: %v\n", err) } _, err = conn.Write([]byte(msg)) if err != nil { // expecting an error after sending a message // to a non-existing client endpoint fmt.Printf("failed sending a message to network: %v\n", err) break } else { fmt.Printf("msg sent: %s", msg) msg = "" } } }}func ReadConsole(network chan <- string) { console := bufio.NewReader(os.Stdin) for { line, err := console.ReadString('\n') if err != nil { panic(err) } else { network <- line } }}func main() { listener, err := net.Listen("tcp", "localhost:6666") if err != nil { panic(err) } println("listening on " + listener.Addr().String()) consoleToNetwork := make(chan string) go AcceptConnections(listener, consoleToNetwork) ReadConsole(consoleToNetwork)}
1 回答
- 1 回答
- 0 关注
- 457 浏览
添加回答
举报
0/150
提交
取消