Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save timsonner/a577c0018b3c31fda6d3bb2d21056c7d to your computer and use it in GitHub Desktop.
GoLang. gob server. Waits for connection from gob client.
// Server
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 received from the client
type Message struct {
Content string // Content field holds the actual message content
}
// handleConnection is a function that handles the communication with a client connection
func handleConnection(conn net.Conn) {
// Create a decoder to decode the binary data received from the client connection
decoder := gob.NewDecoder(conn)
// Create a new empty message to hold the decoded message content
var message Message
// Decode the message received from the client into the message variable
err := decoder.Decode(&message)
if err != nil {
fmt.Println("Error decoding message:", err)
return
}
fmt.Println("Received message:", message.Content) // Print the received message content
conn.Close() // Close the connection with the client
}
func main() {
// Listen for incoming connections on TCP port "localhost:1234"
listener, err := net.Listen("tcp", "localhost:1234")
if err != nil {
fmt.Println("Error listening:", err)
return
}
defer listener.Close() // Close the listener before exiting the main function
fmt.Println("Server started. Waiting for connections...")
// Accept and handle client connections in a loop
for {
// Accept a new client connection
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err)
return
}
// Handle the client connection concurrently in a separate goroutine
go handleConnection(conn)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment