I have a TCP server up and running listetning to a port and a go routine for handeling the connections. I wonder if it's possible to have a go routine running for every connection keeping them alive with net.SetKeepAlive(true)
. Also with error handling so that if the connection times out it will execute cleanup functions like removing the connection from a list?
Handle routine:
func handleConnection(conn net.Conn, rec chan string) {
var item QueItem
buf := make([]byte, bufSize)
l, err := conn.Read(buf)
if err != nil || l < 0 {
fmt.Println("Error reading from conn: ", conn)
fmt.Println("Error reading: ", err)
}
err = json.Unmarshal(buf[:l], &item)
if err != nil {
fmt.Println("Error converting to JSON", jErr)
}
fmt.Printf("Received : %+v
", item)
fmt.Println("recived from:", conn.RemoteAddr())
rec <- item.IP
}
TCPserver:
for {
conn, err := ln.Accept()
if err != nil {
fmt.Println("No accept", err)
log.Println("Unable to accept connection", err)
}
go handleConnection(conn, recived)
}