-
Notifications
You must be signed in to change notification settings - Fork 0
/
unix.go
68 lines (60 loc) · 1.06 KB
/
unix.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
package node
import (
"encoding/json"
"log"
"net"
"github.com/AutoRoute/node/types"
)
type UnixSocket struct {
l net.Listener
d DataConnection
}
// Creates a unix socket which all packets are sent to /from.
func NewUnixSocket(path string, d DataConnection) (*UnixSocket, error) {
l, err := net.Listen("unix", path)
if err != nil {
return nil, err
}
u := &UnixSocket{l, d}
go u.awaitConnection()
return u, nil
}
func (u *UnixSocket) awaitConnection() {
for {
c, err := u.l.Accept()
if err != nil {
log.Print(err)
return
}
go u.sendPackets(c)
go u.receivePackets(c)
}
}
func (u *UnixSocket) sendPackets(c net.Conn) {
dec := json.NewDecoder(c)
for {
p := types.Packet{}
err := dec.Decode(&p)
if err != nil {
log.Print(err)
return
}
err = u.d.SendPacket(p)
if err != nil {
log.Print(err)
}
}
}
func (u *UnixSocket) receivePackets(c net.Conn) {
enc := json.NewEncoder(c)
for p := range u.d.Packets() {
err := enc.Encode(p)
if err != nil {
log.Print(err)
return
}
}
}
func (u *UnixSocket) Close() {
u.l.Close()
}