-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkplclient.go
116 lines (98 loc) · 2.27 KB
/
kplclient.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package kplclientgo
import (
"bufio"
"errors"
"fmt"
"log"
"net"
"net/textproto"
"time"
)
//NewKPLClient returns a new KPLClient
func NewKPLClient(host, port string) *KPLClient {
return &KPLClient{
Host: host,
Port: port,
}
}
//KPLClient represents a client to the KPL Server
type KPLClient struct {
Host string
Port string
// ErrPort is the optional field, which is provided, will cause a server to start and
// on this port and retrieve any error.
// Provide ErrHandler if ErrPort is set.
ErrPort string
ErrHost string
ErrHandler func(data string)
Started bool
Socket net.Conn
SocketChannel chan string
}
//Start starts up a communication channel to the server
func (c *KPLClient) Start() error {
if !c.Started {
address := fmt.Sprintf("%s:%s", c.Host, c.Port)
var err error
c.Socket, err = net.Dial("tcp", address)
if err != nil {
return err
}
if c.ErrPort != "" {
go c.processErrMessage()
}
//synchronize records written across the socket
c.SocketChannel = make(chan string)
go processChannel(c.Socket, c.SocketChannel)
}
c.Started = true
return nil
}
//Stop shutsdown the communication channel to the server
func (c *KPLClient) Stop() {
if c.Started {
c.Socket.Close()
}
}
func processChannel(socket net.Conn, socketChannel chan string) {
for {
//read record from channel
r := <-socketChannel
//write to socket
socket.Write([]byte(r + "\n"))
}
}
func (c *KPLClient) processErrMessage() {
for {
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%s", c.ErrHost, c.ErrPort))
if err != nil {
fmt.Println("Error listening to error port:", err.Error())
time.Sleep(time.Second)
continue
}
log.Println("Error Socket Connection Established")
for {
//Read from err to socket
content, err := Read(conn)
if err != nil {
log.Printf("Listener: Read error: %v", err)
break
}
go c.ErrHandler(content)
}
conn.Close()
}
}
func Read(conn net.Conn) (string, error) {
reader := bufio.NewReader(conn)
tp := textproto.NewReader(reader)
return tp.ReadLine()
}
//PutRecord sends a data record to the KPL server
func (c *KPLClient) PutRecord(record string) error {
if !c.Started {
return errors.New("client is not started")
}
go func() { c.SocketChannel <- record }()
return nil
}