How this infinite for loop is not crashing?
I thought if there were no clients right now, listener.Accept() method were throwing an error which makes the if condition true and the for loop continues to the other iteration until the client connects to a server. Therefore I put fmt.Println("Error")
in the if statement to see if it was working as I guessed. But it wasn't. It did not print "Error" so the program is not going into the if statement when there were no clients.
Can someone explain how this for loop actually works?
func main() {
service := ":1202"
tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
checkError(err)
listener, err := net.ListenTCP("tcp4", tcpAddr)
checkError(err)
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error")
continue
}
}
}
This infinite loop is do the followings:
Wait for the listener.Accept()
to return either with a new connection or an error.
If you got a return value, check for the error. If you have one, log it, or do anything with it, then continue
the loop, so the server can wait for another new connection.
If you don't have an error, simply start a separate go routine which can handle the connection. This way the for loop immediately runs again, so the listener will wait for a new connection while you handle the connection in a separate routine.
See the example:
func main() {
service := ":1202"
tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
checkError(err)
listener, err := net.ListenTCP("tcp4", tcpAddr)
checkError(err)
for {
conn, err := listener.Accept()
if err != nil {
log.Println("We've got an error:",err)
continue
}
go HandleConnection(conn)
}
}