Angel
Angel

Reputation: 99

How do you read from a connection without creating a temp byte slice in Go

The data being sent to my net.Conn are packets using TCP network. These packets are all different sizes. How would I make a buffer that's the exact size of the data coming in? Currently I'm allocating a byte slice which has the biggest packet possible and then slicing it again.

for{
    data := make([]byte, 2097151)
    r, _ := (*c).Read(data)
    data = data[:r]
}

Upvotes: 0

Views: 73

Answers (1)

DTan13
DTan13

Reputation: 438

You can use bufio to read from client

A basic example

func TCPServerReadFromConnection() {
    server, err := net.Listen("tcp", ":8080")
    if err != nil {
        panic(err)
    }
    defer server.Close()

    conn, err := server.Accept()
    if err != nil {
        panic(err)
    }
    defer conn.Close()

    // This is a scanner for accepting the data coming over connection
    scanner := bufio.NewScanner(conn)

    for scanner.Scan() {
        val := scanner.Text()
        fmt.Println(val)
    }
}

Upvotes: 2

Related Questions