There's a func to handle tcp connection:
for {
select {
case conn := <-listen:
go handleClient(conn)
...
}
func handleClient(client net.Conn) {
for {
// ...read from conn
// at some point return
return
}
}
My question is , if you use for
loop, you must write return
or it will be a dead loop. If it returns, this handleClient
function will execute only once. So for
is not necessary here, right? We can still read all of the data Without for
, is this the right way to think ?
A common pattern for a server handling connections might be
func handleClient(conn net.Conn) {
r := bufio.NewReader(conn)
for {
line, err := r.ReadBytes(byte('
'))
switch err {
case nil:
break
case io.EOF:
default:
fmt.Println("ERROR", err)
}
// do something with the data, in this case echo it back
conn.Write(line)
}
}
The for {} loop is necessary to read multiple lines of data from the connection.
If the handleClient can read the input all in one chunk then a loop isn't necessary
So, yes you are right the for {} is not always necessary but it depends what data is being read. Often a loop like this is the best way to read the data