#Net Package Taking Up My Cpu Usage

15 messages · Page 1 of 1 (latest)

humble veldt
umbral prairie
#

you have an infinite loop in handler()

humble veldt
#

ahh

umbral prairie
#

usually you'd read some data into a buffer in this loop

humble veldt
#

ye i made a reader

#

but how am i going to detect if the user disconnected and break the loop

umbral prairie
#

try conn.SetDeadLine

humble veldt
#

what does that do?

umbral prairie
#

you'll get a timeout error if it takes too long to recieve any data

humble veldt
#

is that what set deadline do ?

#

do i error handle it and break the loop

#

or it closes the connection for me

umbral prairie
#

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
#

there's no disconnect messages in TCP, so you either have to send keepalive messages or send a disconnect message yourself