如下代码:
func handlerUpper(conn net.Conn) {
defer recovery()
defer conn.Close()
go func() {
defer recovery()
defer conn.Close()
var buff [512]byte
for {
n, err := conn.Read(buff[0:])
checkPanic(err)
// fmt.Printf("upper reader:% X", buff[0:n])
go ParseUpper(buff[0:n])
}
}()
for {
data := <-upper
n, err := conn.Write(data[0:len(data)])
checkPanic(err)
fmt.Printf("upper writer:% X", data[0:n])
}
}
能把conn.Read()和conn.Write()写在同一个goroutine吗?应该怎么实现?
这段代码还有个问题,可能会执行defer conn.Close()两次,我希望conn.Close()之后能撤销这两个goroutine,应该怎么处理?
要注意 SetReadDeadline()的用法:
func handlerUpper(conn net.Conn) {
defer recovery()
defer conn.Close()
var buff [256]byte
for {
select {
case data := <-upper:
n, err := conn.Write(data[0:len(data)])
checkPanic(err)
fmt.Printf("upper writer:% X", data[0:n])
default:
conn.SetReadDeadline(time.Now().Add(time.Millisecond * 50))
n, err := conn.Read(buff[0:])
if err == nil {
//fmt.Printf("upper reader:% X", buff[0:n])
go ParseUpper(buff[0:n])
} else {
//fmt.Println("timeOut")
}
}
}
}
#1
更多评论