Hi,
I started to learn Go recently and as part of my learning want to implement small network server which will talk with GPS device.
Protocol is very simple: first device sends its identifier, and if server wants to accept data from this device it should reply with 01
otherwise with 00
. Responce should be send as binary packet. Previously, in Python this was done with sending bytes
value b'\x01'
or b'\x00'
.
And here I’m stuck. Using following code I can succesfully receive initial packet with device ID, but I can’t find a way to send responce correctly. As result, second packet is always empty, device does not send any data.
func handleConnection(conn net.Conn) {
remoteAddr := conn.RemoteAddr().String()
fmt.Println("Client connected:", remoteAddr)
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
fmt.Println("Read error", err.Error())
conn.Close()
}
fmt.Println("Received bytes:", n)
fmt.Println("ID", string(buf[2:17]))
err = binary.Write(conn, binary.BigEndian, a)
if err != nil {
fmt.Println("Write error", err.Error())
conn.Close()
}
n, err = conn.Read(buf)
if err != nil {
fmt.Println("Read error", err.Error())
conn.Close()
}
fmt.Println("Received bytes:", n)
fmt.Println("Data", string(buf[:n]))
I also tried to send data as
_, err = conn.Write([]byte{0x01})
and
var a byte = 1
t := new(bytes.Buffer)
err = binary.Write(t, binary.BigEndian, a)
if err != nil {
fmt.Println("binary.Write failed:", err)
}
_, err = conn.Write(t.Bytes())
Am I doing something wrong?
Thanks and sorry for my English.