I am using golang language. Now I have a UDP socket. I start a goroutine to receive the information returned by the server. The code running in goroutine is as follows:
func (udp_client *UDPClient) recvFrom() {
var conns = *udp_client.conn
var err error
for {
readBuff := make([]byte, recvBufferSize)
_, err = conns.Read(readBuff)
if err != nil {
// boomer.RecordFailure("UDP", "RECV", 0.0, err.Error())
log.Error("socket recv error.", zap.String("errMsg", err.Error()))
return
}
udp_client.recvMessage <- readBuff
}
}
How can I close this goroutine.
I tried to close the socket externally and let the program in goroutine exit, but it didn't seem to work. The program in goroutine seems to be stuck.
Thank you for reading. English is not my mother tongue. Please forgive my grammatical mistakes.
Looking forward to your reply, thank you!
CodePudding user response:
I am not sure what you are looking for but ending of the loop is solely dependent on you. Your loop can keep on reading data until it sees some flag (Timer or message of close) to shut it-self down. If you are asking as how to how close it, then use conn.Close().
It will be better to put in a defered sentence, like: defer conn.Close().
CodePudding user response:
By reading the comment of function 'Close()', can saw this:
// Close closes the connection.
// Any blocked Read or Write operations will be unblocked and return errors.
Close() error
So, I guess the problem maybe in somewhere else.