send a message to a tcp server in go

To send a 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.

  2. Convert the message to a byte array using the []byte type.

  3. Write the message to the connection using the connection's Write method.

  4. Close the connection using the connection's Close method.

Here's an example code snippet that demonstrates how to send a message to a TCP server in Go:

main.go
package main

import (
    "fmt"
    "net"
)

func main() {
    // Open a TCP connection to the server
    conn, err := net.Dial("tcp", "localhost:1234")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer conn.Close()

    // Convert the message to a byte array
    message := "Hello, server!"
    byteMessage := []byte(message)

    // Write the message to the connection
    _, err = conn.Write(byteMessage)
    if err != nil {
        fmt.Println(err)
        return
    }
}
503 chars
28 lines

related categories

gistlibby LogSnag