Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang net.Conn does not have Data available property

Tags:

c#

go

I am new to go. I have been coding in C# but I need server as well. So I have written a server:

func ServeToClient(client net.Conn) {
for {
    fmt.Fprintln(client,"Serving you!")
    buffer:=make([]byte,1024)
    _, err :=bufio.NewReader(client).Read(buffer)
    if err!=nil{
        fmt.Println(err)
        client.Close()
        fmt.Println("Disconnected duet to the error: ",err.Error())
        return
    }
    data := string(buffer)
    fmt.Println(data)
    command := data[0:2]
    i,err := strconv.Atoi(command)
    if err!=nil {
        fmt.Println(err)
        return
    }
}

But it sees the data as :

{"id":"009","username":"Bungler"}??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

And I guess it is owing to excess of byte byte array(it is in 1024 length). Is there any property (like in C# Socket.Availabe) to create my byte array properly?


1 Answers

According with Read() you're ignoring the number of bytes read into variable buffer, on this line:

_, err := bufio.NewReader(client).Read(buffer)

Just add a new variable n to store the number of bytes:

n, err := bufio.NewReader(client).Read(buffer)

and then you can take only that number of bytes from your buffer that has length of 1024:

data := string(buffer[:n])

Edit:

Other alternatives:

  • you could use a json Decoder something like this: json.NewDecoder(client).Decode(&pointer_to_struct_or_map)
  • ioutil.ReadAll(client)
  • save each 1024 bytes into a Buffer and then you can use Bytes()
like image 74
Yandry Pozo Avatar answered Feb 01 '26 11:02

Yandry Pozo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!