Oh I’m pretty sure that’s just happening because you are inside of a for loop and after you read the packet, the next time you try to read again, there’s nothing else to read.
For example:
Server:
package main
import (
"bufio"
"fmt"
"io"
"log"
"net"
)
func handleConn(c net.Conn) {
defer c.Close()
r := bufio.NewReader(c)
for {
var hdr [3]byte
// Read into the header.
n, err := io.ReadFull(r, hdr[:])
// Make sure 3 bytes were read into the header.
if n < 3 || err != nil && err != io.EOF {
log.Fatalf("invalid packet header %v\n", err)
}
// Make sure first 2 bytes are 0x78.
if hdr[0] != 0x78 || hdr[1] != 0x78 {
log.Fatalln("packet header start is not 0x78 0x78")
}
// Get packet length.
ln := int(hdr[2])
data := make([]byte, ln)
n, err = io.ReadFull(r, data)
if n < 2 || err != nil && err != io.EOF {
log.Fatalf("error reading packet data, %v\n", err)
}
// Extract the crc from the last 2 bytes of the data.
crc := data[len(data)-2:]
// Read the final 2 bytes from the packet's end.
end := make([]byte, 2)
// Read the last 2 bytes.
n, err = io.ReadFull(r, end)
// Make sure 2 bytes were read into end.
if n < 2 || err != nil && err != io.EOF {
log.Fatalf("invalid packet end %v\n", err)
}
// Make sure the 2 end bytes are correct.
if end[0] != 0x0d || end[1] != 0x0a {
log.Fatalln("packet end is not 0x0d 0x0a")
}
fmt.Printf("header: %x\ndata: %x\ncrc: %x\nend: %x\n", hdr, data, crc, end)
}
}
func main() {
l, err := net.Listen("tcp", ":9000")
if err != nil {
log.Fatalln(err)
}
for {
c, err := l.Accept()
if err != nil {
fmt.Println(err)
continue
}
go handleConn(c)
}
}
Client:
package main
import (
"log"
"net"
)
func main() {
packets := []byte{
0x78, 0x78, 0x0a, 0x13, 0x46, 0x00, 0x43, 0x00, 0x01, 0x00, 0x14, 0xcb, 0x23, 0x0d, 0x0a,
0x78, 0x78, 0x0a, 0x14, 0x47, 0x00, 0x43, 0x00, 0x01, 0x00, 0x14, 0xcb, 0x23, 0x0d, 0x0a,
}
c, err := net.Dial("tcp", ":9000")
if err != nil {
log.Fatalln(err)
}
defer c.Close()
_, err = c.Write(packets)
if err != nil {
log.Fatalln(err)
}
}
You will get the output for the first 2 packets, but then an EOF.