From e9d72b09fed81a7c1598a96e146b23517c6b395e Mon Sep 17 00:00:00 2001 From: raul Date: Mon, 3 Jun 2024 08:52:47 +0200 Subject: [PATCH] Add gob-net exercise --- gob-net/go.mod | 3 +++ gob-net/main.go | 54 ++++++++++++++++++++++++++++++++++++++++++ gob-net/sendmessage.go | 34 ++++++++++++++++++++++++++ 3 files changed, 91 insertions(+) create mode 100644 gob-net/go.mod create mode 100644 gob-net/main.go create mode 100644 gob-net/sendmessage.go diff --git a/gob-net/go.mod b/gob-net/go.mod new file mode 100644 index 0000000..f5b12f4 --- /dev/null +++ b/gob-net/go.mod @@ -0,0 +1,3 @@ +module gob-net + +go 1.22.3 diff --git a/gob-net/main.go b/gob-net/main.go new file mode 100644 index 0000000..2ac4924 --- /dev/null +++ b/gob-net/main.go @@ -0,0 +1,54 @@ +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) +} diff --git a/gob-net/sendmessage.go b/gob-net/sendmessage.go new file mode 100644 index 0000000..8e7724e --- /dev/null +++ b/gob-net/sendmessage.go @@ -0,0 +1,34 @@ +package main + +import ( + "encoding/gob" + "log" + "net" +) + +type Information struct { + Name string + Age int + FavouriteSong string + IsAdmin bool +} + +func SendGob() { + info := Information{ + Name: "Raul", + Age: 19, + FavouriteSong: "Unknown", + IsAdmin: true, + } + + conn, err := net.Dial("tcp", "127.0.0.1:1302") + if err != nil { + log.Fatal(err) + } + defer conn.Close() + enc := gob.NewEncoder(conn) + err = enc.Encode(info) + if err != nil { + log.Fatalf("Error happened encoding data: %v\n", err) + } +}