diff options
| author | Andrew <saintruler@gmail.com> | 2021-04-26 23:16:32 +0400 |
|---|---|---|
| committer | Andrew <saintruler@gmail.com> | 2021-04-26 23:16:32 +0400 |
| commit | 82e4202ba125d4ebc1e7ab75e52938c0b7a97071 (patch) | |
| tree | 4a45a1b6bda945dd83740eed13aafa8fb4bef24e /server/utils.go | |
| parent | 431ea111d2a5167b65a84620c16e28fd463f7985 (diff) | |
Added second listener to server and rewrote client in go.
Diffstat (limited to 'server/utils.go')
| -rw-r--r-- | server/utils.go | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/server/utils.go b/server/utils.go new file mode 100644 index 0000000..cd2069f --- /dev/null +++ b/server/utils.go @@ -0,0 +1,70 @@ +package main + +import ( + "encoding/json" + "net" +) + +const ( + MESSAGE = "message" + AUTHENTICATE = "authenticate" + RENAME = "rename" +) + +const ( + SUCCESS = "success" + FAILURE = "failure" +) + +type Message struct { + Type string + Data string + User string +} + +func (msg *Message) serialize() string { + data, _ := json.Marshal(msg) + return string(data) +} + +type Response struct { + Status string + Data string +} + +func toBytes(num uint32) []byte { + buf := make([]byte, 4) + var mask uint32 = 0x00FF + for i := 0; i < 4; i += 1 { + buf[4-i-1] = byte(num & mask) + num >>= 8 + } + return buf +} + +func fromBytes(data []byte) uint32 { + var num uint32 + for i := 0; i < 4; i += 1 { + num += uint32(data[i] << ((4 - i - 1) * 8)) + } + return num +} + +func sendMessage(conn net.Conn, message []byte) error { + size := uint32(len(message)) + + data := append(toBytes(size), message...) + _, err := conn.Write(data) + if err != nil { + return err + } + + return nil +} + +func parseMessage(data []byte) Message { + var m Message + // TODO(andrew): Добавить обработку ошибок + json.Unmarshal(data, &m) + return m +} |