pixclient/pixclient.go

74 lines
1.6 KiB
Go
Raw Normal View History

2017-05-26 13:33:18 +00:00
package pixclient
import (
2017-05-27 14:27:33 +00:00
"bufio"
"errors"
2017-05-26 13:33:18 +00:00
"net"
"strconv"
2017-05-27 14:27:33 +00:00
"strings"
2017-05-26 13:33:18 +00:00
)
type Client struct {
connection net.Conn
2017-05-27 14:27:33 +00:00
width int
height int
2017-05-26 13:33:18 +00:00
}
func Init(addr net.IP, port int) *Client {
var client Client
connection, err := net.Dial("tcp", addr.String()+":"+strconv.Itoa(port))
check(err)
2017-05-27 14:27:33 +00:00
client.connection = connection
client.Size()
2017-05-26 13:33:18 +00:00
return &client
}
2017-05-27 14:27:33 +00:00
func (Client *Client) WritePixel(x, y int, r, g, b, a byte) error {
2017-05-26 13:33:18 +00:00
var bytes []byte
2017-05-27 14:27:33 +00:00
if x <= 0 || y <= 0 || x >= Client.width || y >= Client.height {
return errors.New("Pixel out of range.")
}
2017-05-26 13:33:18 +00:00
bytes = append(appendTwoDigitHex(appendTwoDigitHex(appendTwoDigitHex(appendTwoDigitHex(append(append(append(append(append(
bytes, []byte("PX ")...),
[]byte(strconv.FormatInt(int64(x), 10))...),
[]byte(" ")...),
[]byte(strconv.FormatInt(int64(y), 10))...),
[]byte(" ")...),
r),
g),
b),
a),
[]byte("\n")...)
Client.connection.Write(bytes)
//
//Client.connection.Write([]byte(
// fmt.Sprintf("PX %d %d %X\n", x, y, []byte{r, g, b, a})))
2017-05-27 14:27:33 +00:00
return nil
2017-05-26 13:33:18 +00:00
}
2017-05-27 14:27:33 +00:00
func (Client *Client) Size() (int, int) {
Client.connection.Write([]byte("SIZE\n"))
reader := bufio.NewReader(Client.connection)
size, err := reader.ReadBytes('\n')
check(err)
sizeString := string(size)
sizeArray := strings.Split(sizeString, " ")
Client.width, _ = strconv.Atoi(sizeArray[1])
Client.height, _ = strconv.Atoi(sizeArray[2])
return Client.width, Client.height
}
2017-05-26 13:33:18 +00:00
func appendTwoDigitHex(bytes []byte, val byte) []byte {
if val < 0x10 {
bytes = append(bytes, []byte("0")...)
}
return strconv.AppendInt(bytes, int64(val), 16)
}
func check(e error) {
if e != nil {
panic(e)
}
}