forked from childe/gohangout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp_input.go
113 lines (97 loc) · 2.07 KB
/
tcp_input.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
package input
import (
"bufio"
"net"
"github.com/childe/gohangout/codec"
"github.com/childe/gohangout/topology"
"github.com/golang/glog"
)
type TCPInput struct {
config map[interface{}]interface{}
network string
address string
decoder codec.Decoder
l net.Listener
messages chan []byte
stop bool
}
func readLine(scanner *bufio.Scanner, c net.Conn, messages chan<- []byte) {
for scanner.Scan() {
t := scanner.Bytes()
buf := make([]byte, len(t))
copy(buf, t)
messages <- buf
}
if err := scanner.Err(); err != nil {
glog.Errorf("read from %v->%v error: %v", c.RemoteAddr(), c.LocalAddr(), err)
}
c.Close()
}
func init() {
Register("TCP", newTCPInput)
}
func newTCPInput(config map[interface{}]interface{}) topology.Input {
var codertype string = "plain"
if v, ok := config["codec"]; ok {
codertype = v.(string)
}
p := &TCPInput{
config: config,
decoder: codec.NewDecoder(codertype),
messages: make(chan []byte, 10),
}
if v, ok := config["max_length"]; ok {
if max, ok := v.(int); ok {
if max <= 0 {
glog.Fatal("max_length must be bigger than zero")
}
} else {
glog.Fatal("max_length must be int")
}
}
p.network = "tcp"
if network, ok := config["network"]; ok {
p.network = network.(string)
}
if addr, ok := config["address"]; ok {
p.address = addr.(string)
} else {
glog.Fatal("address must be set in TCP input")
}
l, err := net.Listen(p.network, p.address)
if err != nil {
glog.Fatal(err)
}
p.l = l
go func() {
for !p.stop {
conn, err := l.Accept()
if err != nil {
if p.stop {
return
}
glog.Error(err)
} else {
scanner := bufio.NewScanner(conn)
if v, ok := config["max_length"]; ok {
max := v.(int)
scanner.Buffer(make([]byte, 0, max), max)
}
go readLine(scanner, conn, p.messages)
}
}
}()
return p
}
func (p *TCPInput) ReadOneEvent() map[string]interface{} {
text, more := <-p.messages
if !more || text == nil {
return nil
}
return p.decoder.Decode(text)
}
func (p *TCPInput) Shutdown() {
p.stop = true
p.l.Close()
close(p.messages)
}