Add gob-net exercise

This commit is contained in:
raul 2024-06-03 08:52:47 +02:00
parent c96dcea8ac
commit e9d72b09fe
3 changed files with 91 additions and 0 deletions

3
gob-net/go.mod Normal file
View File

@ -0,0 +1,3 @@
module gob-net
go 1.22.3

54
gob-net/main.go Normal file
View File

@ -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)
}

34
gob-net/sendmessage.go Normal file
View File

@ -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)
}
}