-
Notifications
You must be signed in to change notification settings - Fork 0
/
protocolmux.go
111 lines (94 loc) · 1.82 KB
/
protocolmux.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
package protocolmux
import (
"bytes"
"fmt"
"io"
"log"
"net"
)
type handler struct {
prefixes [][]byte
conns chan (*conn)
mux *Mux
}
func (h *handler) Accept() (net.Conn, error) {
c, ok := <-h.conns
if !ok {
return nil, io.EOF
}
return c, nil
}
func (h *handler) Addr() net.Addr {
return h.mux.L.Addr()
}
func (h *handler) Close() error {
for i, handler := range h.mux.handlers {
if handler == h {
h.mux.handlers = append(h.mux.handlers[:i], h.mux.handlers[i+1:]...)
}
}
close(h.conns)
return nil
}
type Mux struct {
L net.Listener
handlers []*handler
}
type conn struct {
net.Conn
prefix []byte
}
func (m *Mux) ListenTo(prefixes [][]byte) net.Listener {
h := &handler{
prefixes: prefixes,
conns: make(chan (*conn)),
mux: m,
}
m.handlers = append(m.handlers, h)
return h
}
func (m *Mux) l(v ...interface{}) {
fmt.Println(append([]interface{}{"MUX:"}, v...)...)
}
func (m *Mux) Listen() error {
m.l("starting listener")
if m.L == nil {
return fmt.Errorf("listener not defined")
}
for {
m.l("Waiting for connection")
conn, err := m.L.Accept()
m.l("Got new Connection", conn.RemoteAddr())
fmt.Println()
if err != nil {
return err
}
go m.handleConn(conn)
}
}
func (c *conn) Read(b []byte) (int, error) {
if len(c.prefix) == 0 {
return c.Conn.Read(b)
}
n := copy(b, c.prefix)
c.prefix = c.prefix[n:] // BUG?
return n, nil
}
func (m *Mux) handleConn(c net.Conn) {
buf := make([]byte, 1024)
n, err := c.Read(buf)
if err != nil {
log.Println("erro while handling a connection:", err)
}
for _, handler := range m.handlers {
for _, prefix := range handler.prefixes {
if bytes.HasPrefix(buf[:n], prefix) {
c := &conn{Conn: c, prefix: buf[:n]}
handler.conns <- c
return
}
}
}
log.Println("no protocol for connection")
c.Close()
}