-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathhare.go
81 lines (67 loc) · 1.65 KB
/
hare.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
package hare
import (
"bufio"
"net"
)
const (
connectionHost = "localhost"
connectionType = "tcp"
)
// Listener tools for socket listening
type Listener struct {
SocketListener net.Listener
HasNewMessages func() bool
GetMessage func() string
Stop func()
}
// MessageManager manages message storage
type MessageManager struct {
HasNewMessages bool
Message string
}
func listening(listener Listener, messageManager *MessageManager, running *bool) error {
for *running {
c, _ := listener.SocketListener.Accept()
message, _ := bufio.NewReader(c).ReadString('\n')
messageManager.Message = message
messageManager.HasNewMessages = true
}
listener.SocketListener.Close()
return nil
}
// Listen to socket port
func Listen(port string) (Listener, error) {
var err error
var listener Listener
var messageManager MessageManager
listener.SocketListener, err = net.Listen(connectionType, connectionHost+":"+port)
if err != nil {
return listener, err
}
// GetMessage return the last message
listener.GetMessage = func() string {
messageManager.HasNewMessages = false
return messageManager.Message
}
// HasNewMessages return if there's new messages on socket
listener.HasNewMessages = func() bool {
return messageManager.HasNewMessages
}
running := true
// Stop the listener
listener.Stop = func() {
running = false
}
go listening(listener, &messageManager, &running)
return listener, nil
}
// Send message to socket port
func Send(port, message string) error {
conn, err := net.Dial(connectionType, connectionHost+":"+port)
if err != nil {
return err
}
defer conn.Close()
conn.Write([]byte(message))
return nil
}