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?
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:
json.NewDecoder(client).Decode(&pointer_to_struct_or_map)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With