Skip to content

Instantly share code, notes, and snippets.

@timsonner
Last active July 13, 2023 22:52
Show Gist options
  • Select an option

  • Save timsonner/b249572ca0594f1326164052f9a4f9f4 to your computer and use it in GitHub Desktop.

Select an option

Save timsonner/b249572ca0594f1326164052f9a4f9f4 to your computer and use it in GitHub Desktop.
GoLang. gob client. Connects and sends message to gob server.
// Client
package main
import (
"encoding/gob" // Package for encoding and decoding data
"fmt" // Package for formatted I/O
"net" // Package for network operations
)
// Message represents the structure of the message sent from the client to the server
type Message struct {
Content string // Content field holds the actual message content
}
func main() {
// Establish a connection to the server at "localhost:1234" using TCP protocol
conn, err := net.Dial("tcp", "localhost:1234")
if err != nil {
fmt.Println("Error connecting to server:", err)
return
}
defer conn.Close() // Close the connection before exiting the main function
// Create an encoder to encode Go values into a binary format to be sent over the network connection
encoder := gob.NewEncoder(conn)
// Create a new message with the content "Hello, server!"
message := Message{"Hello, server!"}
// Encode the message and send it to the server through the connection
err = encoder.Encode(message)
if err != nil {
fmt.Println("Error encoding message:", err)
return
}
fmt.Println("Message sent to server:", message.Content) // Print the message content sent to the server
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment