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)
Adding to Yandry Pozo's answer: n
could be more than 1024
or maybe you don't get the whole message in one call to Read
. (Over a network that is all possible.)
So to get a reliable communication protocol you should define some message format, where the receiver can determine, wether the message is complete.
For example you could do a simple form of framing and send the length of the message in the first 4 bytes. You could then read until you get 4 bytes and then call Read
repeatedly, until you got the whole message.