From 4fba091d4d23a38b901e6345a4330aed79c02ea8 Mon Sep 17 00:00:00 2001 From: qowevisa Date: Wed, 1 May 2024 17:20:27 +0300 Subject: [PATCH] Add communication package --- communication/protocol.go | 55 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 communication/protocol.go diff --git a/communication/protocol.go b/communication/protocol.go new file mode 100644 index 0000000..7de91ff --- /dev/null +++ b/communication/protocol.go @@ -0,0 +1,55 @@ +package communication + +import ( + "bytes" + "encoding/gob" +) + +const ( + SERVER_COMMAND = 1 + iota + CLIENT_RESPONSE + P2P_MESSAGE +) + +const ( + V1 = 1 + iota +) + +const ( + NICKNAME = 1 +) + +type communicationMessage struct { + Type uint8 + Data []byte +} + +func AskClientNickname() ([]byte, error) { + c := communicationMessage{ + Type: SERVER_COMMAND, + Data: []byte{NICKNAME}, + } + return c.Bytes() +} + +func (c *communicationMessage) Bytes() ([]byte, error) { + var buf bytes.Buffer + encoder := gob.NewEncoder(&buf) + err := encoder.Encode(c) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +func Decode(serverBytes []byte) (*communicationMessage, error) { + var c communicationMessage + buf := bytes.NewBuffer(serverBytes) + decoder := gob.NewDecoder(buf) + err := decoder.Decode(&c) + if err != nil { + return nil, err + } + + return &c, nil +}