Scontrini-TUI-Client/api/protocol.go

79 lines
1.6 KiB
Go

package api
import (
"encoding/binary"
"encoding/json"
"fmt"
"net"
)
var (
printer_server_IP = net.ParseIP("127.0.0.1")
printer_server_port = 4444
)
/**
* All messages from and to the API must have the first 4 bytes set to represent
* the length of the message, followed by the message itself
*/
func sendJSONToServer[T JSONCommand](socket *net.TCPConn, json_command T) (*net.TCPConn, error) {
json_data, err := json.Marshal(json_command)
if err != nil {
return nil, err
}
// in case a socket doesn't already exist create a new one
if socket == nil {
socket, err = net.DialTCP("tcp4", nil, &net.TCPAddr{printer_server_IP, printer_server_port, ""})
}
if err != nil {
return nil, err
}
// the first 4 bytes must be the length of the message
to_send := make([]byte, 4)
binary.LittleEndian.PutUint32(to_send, uint32(len(json_data)))
to_send = append(to_send, json_data...)
socket.Write([]byte(to_send))
return socket, nil
}
func receiveJSONFromServer[T JSONReceived](socket *net.TCPConn, json_received *T) (*net.TCPConn, error) {
var err error
// in case a socket doesn't already exist create a new one
if socket == nil {
fmt.Println("nil")
socket, err = net.DialTCP("tcp4", nil, &net.TCPAddr{printer_server_IP, printer_server_port, ""})
}
if err != nil {
return nil, err
}
// the first 4 bytes are the length of the message
b := make([]byte, 4)
_, err = socket.Read(b[0:])
if err != nil {
return nil, err
}
body_length := binary.LittleEndian.Uint32(b)
body := make([]byte, body_length)
_, err = socket.Read(body[0:])
err = json.Unmarshal(body, json_received)
if err != nil {
return nil, err
}
return socket, nil
}