Add communication package

This commit is contained in:
qowevisa 2024-05-01 17:20:27 +03:00
parent 2b767e0b3e
commit 4fba091d4d

55
communication/protocol.go Normal file
View File

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