https://gyazo.com/e87b9754cdeefb55f8525f8ba274868d <- Image of whats happening and the code behind it
#Net Package Taking Up My Cpu Usage
15 messages · Page 1 of 1 (latest)
you have an infinite loop in handler()
ahh
usually you'd read some data into a buffer in this loop
ye i made a reader
but how am i going to detect if the user disconnected and break the loop
try conn.SetDeadLine
what does that do?
you'll get a timeout error if it takes too long to recieve any data
is that what set deadline do ?
do i error handle it and break the loop
or it closes the connection for me
something like this should work
for {
buf := make([]byte, 64) // read 64 bytes
conn.SetDeadline(time.Now().Add(5*time.Second)) // set a timeout of 5 seconds
_, err = conn.Read(buf)
if err, ok := err.(net.Error); ok && err.Timeout() {
break
} else {
fmt.Println(err)
}
}
// disconnected
you probably also have to send keepalive messages: https://pkg.go.dev/net#TCPConn.SetKeepAlive
there's no disconnect messages in TCP, so you either have to send keepalive messages or send a disconnect message yourself