golang-exercises/gob-net/main.go

55 lines
998 B
Go
Raw Normal View History

2024-06-03 08:52:47 +02:00
package main
import (
"encoding/gob"
"fmt"
"log"
"net"
"os"
)
type ReceivedInformation struct {
Name string
Age int
FavouriteSong string
IsAdmin bool
}
func main() {
if len(os.Args) != 1 {
fmt.Println("Start client")
SendGob()
os.Exit(0)
}
ln, err := net.Listen("tcp", ":1302")
if err != nil {
log.Fatal(err)
}
defer ln.Close()
log.Print("Listening on port 1302...")
for {
c, err := ln.Accept()
if err != nil {
log.Print(err)
}
defer c.Close()
handleConn(c)
}
}
func handleConn(c net.Conn) {
dec := gob.NewDecoder(c)
var received ReceivedInformation
err := dec.Decode(&received)
if err != nil {
log.Printf("Error happened decoding gob: %v\n", err)
}
if received.IsAdmin == true {
fmt.Println("Message received from an administrator!")
} else {
fmt.Println("This is not an admin")
}
fmt.Printf("Received information:\nName: %v\nAge: %v\nFavourite song: %v\n", received.Name, received.Age, received.FavouriteSong)
}