send a binary message to a tcp server in go

To send a binary message to a TCP server in Go, you can follow these steps:

  1. Open a TCP connection to the server using the net package's Dial function.
    main.go
    conn, err := net.Dial("tcp", "example.com:8080")
    if err != nil {
        // handle error
    }
    
    87 chars
    5 lines
  2. Convert your message to binary form using the encoding/binary package.
    main.go
    messageId := uint16(42)
    messageData := "Hello, server!"
    messageLength := uint32(len(messageData))
    message := new(bytes.Buffer)
    binary.Write(message, binary.LittleEndian, messageId)
    binary.Write(message, binary.LittleEndian, messageLength)
    binary.Write(message, binary.LittleEndian, []byte(messageData))
    
    303 chars
    8 lines
  3. Send the binary message to the server using the conn object's Write method.
    main.go
    _, err = conn.Write(message.Bytes())
    if err != nil {
        // handle error
    }
    
    75 chars
    5 lines
  4. Read the response from the server using the conn object's Read method.
    main.go
    response := make([]byte, 1024)
    numBytes, err := conn.Read(response)
    if err != nil {
        // handle error
    }
    fmt.Println(string(response[:numBytes]))
    
    147 chars
    7 lines
  5. Close the TCP connection using the conn object's Close method.
    main.go
    conn.Close()
    
    13 chars
    2 lines

related categories

gistlibby LogSnag