Hello everyone! I'm building a simple tcp chat application where I read data from connections and broadcast it to the other active connections in the session.
I have the following function which is spawned as** go routine** for each incoming connection in order to read data from sent by the connection stream:
func read(conn net.Conn, msgCh chan Message) {
buffer := []byte{}
for {
_, err := conn.Read(buffer)
if err != nil {
fmt.Println(err)
}
message := NewMessage(string(buffer), conn.RemoteAddr().String())
msgCh <- message
fmt.Printf("[MESSAGE SENT] %#v", message)
buffer = []byte{}
}
}
The issue comes because it starts an infinite loop where just reading empty content.
I'm curious about why this happens. Also I made a little bit of research and I noticed that if I put some size on buffer initialization (buffer := make([]byte{}, 1024), it works; but I'm not sure why.