Skip to content

Instantly share code, notes, and snippets.

@beglov
Last active October 11, 2024 23:09
Show Gist options
  • Save beglov/592114644884fe2d31065ff57dfc2e56 to your computer and use it in GitHub Desktop.
Save beglov/592114644884fe2d31065ff57dfc2e56 to your computer and use it in GitHub Desktop.
Golang TCP client receiving/sending binary data
package main
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"log"
"net"
)
type SentMessage struct {
Version int16
TransmitterID int32
MessageType int16
DataType int16
Time uint32
SystolicPressure uint16
DiastolicPressure uint16
Pulse uint16
CRC uint16
}
type ReceivedMessage struct {
Version int16
DataStatus int32
}
func main() {
conn, err := net.Dial("tcp", "81.200.90.23:8585")
if err != nil {
log.Fatal(err)
}
msg := SentMessage{
Version: 3,
TransmitterID: 95263316,
MessageType: 3,
DataType: 3082,
Time: 3822627258,
SystolicPressure: 140,
DiastolicPressure: 76,
Pulse: 95,
CRC: 56862,
}
err = binary.Write(conn, binary.BigEndian, msg)
if err != nil {
log.Fatal(err)
}
buf := make([]byte, 500)
size, err := conn.Read(buf)
if err != nil {
if err == io.EOF {
return
}
log.Fatal(err)
}
message := buf[:size]
reader := bytes.NewBuffer(message)
data := ReceivedMessage{}
err = binary.Read(reader, binary.BigEndian, &data)
if err != nil {
log.Fatal(err)
}
fmt.Println("Version:", data.Version)
fmt.Printf("DataStatus: 0x%08X\n", data.DataStatus)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment