send a binary message to a udp server in go

To send a binary message to a UDP (User Datagram Protocol) server in Go, you can follow these steps:

  1. Import the net package to work with UDP connections:
main.go
import "net"
13 chars
2 lines
  1. Declare the server address and create a UDP connection:
main.go
serverAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:8000")
if err != nil {
    log.Fatal(err)
}

conn, err := net.DialUDP("udp", nil, serverAddr)
if err != nil {
    log.Fatal(err)
}
defer conn.Close()
206 chars
11 lines
  1. Prepare your binary data in byte array format:
main.go
message := []byte{0x01, 0x02, 0x03, 0x04}
42 chars
2 lines
  1. Send the binary message using the Write method:
main.go
_, err = conn.Write(message)
if err != nil {
    log.Fatal(err)
}
66 chars
5 lines

Putting it all together, the code for sending a binary message to a UDP server in Go would look like this:

main.go
import (
    "log"
    "net"
)

func main() {
    serverAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:8000")
    if err != nil {
        log.Fatal(err)
    }

    conn, err := net.DialUDP("udp", nil, serverAddr)
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    message := []byte{0x01, 0x02, 0x03, 0x04}

    _, err = conn.Write(message)
    if err != nil {
        log.Fatal(err)
    }
}
420 chars
25 lines

related categories

gistlibby LogSnag