I have a TCP server which receives responds hex encoded messages. This works fine with lower traffic. It can handle 100, 200 messages per second. I face GC (garbage collection) issue at higher traffic and scripts stops responding and recovers after some time. Appreciate your valuable inputs on this.
var running bool = true
func main() {
flag.IntVar(&lport, "lport", 5555, "Listen Port")
flag.Parse()
sockAddr := fmt.Sprintf(":%d", lport)
TcpService(sockAddr)
}
func TcpService(addr string) {
sockAddr, err := net.ResolveTCPAddr("tcp", addr)
checkError(err)
listener, err := net.ListenTCP("tcp", sockAddr)
checkError(err)
for running {
conn, err := listener.Accept()
if err != nil {
continue
}
go serveConnection(conn, addr)
}
}
func serveConnection(conn net.Conn, addr string) {
defer conn.Close()
var buf []byte
data := make([]byte, 1024*1024)
for running {
n, err := conn.Read(data[0:])
if err == io.EOF {
//conn.Close()
//return
}
if n > 0 {
buf = append(buf, data[0:n]...)
for {
if len(buf) > 4 {
// Every message is of fixed length and length is encoded in buf[1:4]
msgLen := decodeLength(buf[1:4])
if len(buf) >= msgLen {
go handleMsg(conn, buf[:msgLen])
buf = buf[msgLen:]
} else {
break
}
} else {
break
}
}
}
}
}
func handleMsg(conn net.Conn, buf []byte) {
/* validate the recieved message ie buf
....
*/
var resp []byte
ressp = append(resp, value1...)
ressp = append(resp, value2...)
ressp = append(resp, value3...)
ressp = append(resp, value4...)
//resp is a hex coded message ( hex bytes) of length varying from 1k to 5k bytes
conn.Write(resp)
}