Saturday, September 9, 2017

Trouble reading packets from a socket in Go

Trouble reading packets from a socket in Go

buf needs to have a definite size. 0-length slice won't work.

Declare it as:

var buf = make([]byte, 1024)

func handleClient(conn net.Conn) {
        defer conn.Close()

        var buf [512]byte

        for {
                n, err := conn.Read(buf[0:])

                if err != nil {
                        fmt.Printf("%v\n", err.Error())
                        return
                }

                fmt.Printf("Got: %d, %s\n", n, buf)

                str := strings.Repeat("A", 16000000)
                _, err2 := conn.Write([]byte(str))

                if err2 != nil {
                        fmt.Printf("%v\n", err.Error())
                        return
                }
        }
}

Reference:

https://stackoverflow.com/questions/2270670/trouble-reading-from-a-socket-in-go

No comments: