major refactoring :/
All checks were successful
Build and Publish / BuildAndDeploy (push) Successful in 1m56s
All checks were successful
Build and Publish / BuildAndDeploy (push) Successful in 1m56s
This commit is contained in:
103
tcp-client.go
Normal file
103
tcp-client.go
Normal file
@@ -0,0 +1,103 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
*TCPClient
|
||||
}
|
||||
|
||||
func Dial(address string) (*Client, error) {
|
||||
|
||||
mux, err := NewTCPClient(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client := &Client{
|
||||
TCPClient: mux,
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
type TCPClient struct {
|
||||
net.Conn
|
||||
Errors chan error
|
||||
ErrorCount int
|
||||
address string
|
||||
*PacketQueue
|
||||
}
|
||||
|
||||
func NewTCPClient(address string) (*TCPClient, error) {
|
||||
connection, err := net.Dial("tcp", address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &TCPClient{
|
||||
Errors: make(chan error),
|
||||
ErrorCount: 0,
|
||||
Conn: connection,
|
||||
address: address,
|
||||
PacketQueue: NewPacketQueue(connection),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (m *TCPClient) Connect() error {
|
||||
if m.Conn == nil {
|
||||
connection, err := net.Dial("tcp", m.address)
|
||||
if err != nil {
|
||||
|
||||
m.Errors <- err
|
||||
m.ErrorCount++
|
||||
|
||||
return err
|
||||
}
|
||||
m.ErrorCount = 0
|
||||
m.Conn = connection
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *TCPClient) Close() {
|
||||
m.Conn.Close()
|
||||
}
|
||||
|
||||
func (m *TCPClient) SendPacket(messageType uint16, data []byte) error {
|
||||
err := m.Connect()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = binary.Write(m.Conn, binary.LittleEndian, Packet{
|
||||
Version: 1,
|
||||
MessageType: messageType,
|
||||
DataLength: uint16(len(data)),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = m.Conn.Write(data)
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *TCPClient) SendPacketFn(messageType uint16, datafn func(w io.Writer) error) error {
|
||||
data, err := GetData(datafn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return m.SendPacket(messageType, data)
|
||||
}
|
||||
|
||||
func (m *TCPClient) Call(messageType uint16, responseType uint16, data []byte) ([]byte, error) {
|
||||
err := m.SendPacket(messageType, data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
packet, err := m.Expect(responseType, time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return packet.Data, nil
|
||||
}
|
||||
Reference in New Issue
Block a user