-
Notifications
You must be signed in to change notification settings - Fork 6
/
server.go
83 lines (72 loc) · 2.12 KB
/
server.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
package telnet
import (
"net"
)
// Option functions add handling of a telnet option to a Server. The Option
// function takes a connection (which it can store but needn't) and returns a
// Negotiator; it is up to the Option function whether a single instance of
// the Negotiator is reused or if a new instance is created for each connection.
type Option func(c *Connection) Negotiator
// Handler is a telnet connection handler. The Handler passed to a server will
// be called for all incoming connections.
type Handler interface {
HandleTelnet(conn *Connection)
}
// HandleFunc makes it easy to pass a function as a Handler instead of a full
// type.
type HandleFunc func(conn *Connection)
// HandleTelnet implements Handler, and simply calls the function.
func (f HandleFunc) HandleTelnet(conn *Connection) {
f(conn)
}
// Server listens for telnet connections.
type Server struct {
// Address is the addres the Server listens on.
Address string
handler Handler
options []Option
listener net.Listener
quitting bool
}
// NewServer constructs a new telnet server.
func NewServer(addr string, handler Handler, options ...Option) *Server {
return &Server{Address: addr, handler: handler, options: options}
}
// Serve runs the telnet server. This function does not return and
// should probably be run in a goroutine.
func (s *Server) Serve(l net.Listener) error {
s.listener = l
s.Address = s.listener.Addr().String()
for {
c, err := s.listener.Accept()
if err != nil {
if s.quitting {
return nil
}
return err
}
conn := NewConnection(c, s.options)
go func() {
s.handler.HandleTelnet(conn)
conn.Conn.Close()
}()
}
}
// ListenAndServe runs the telnet server by creating a new Listener using the
// current Server.Address, and then calling Serve().
func (s *Server) ListenAndServe() error {
l, err := net.Listen("tcp", s.Address)
if err != nil {
return err
}
return s.Serve(l)
}
// Stop the telnet server. This stops listening for new connections, but does
// not affect any active connections already opened.
func (s *Server) Stop() {
if s.quitting {
return
}
s.quitting = true
s.listener.Close()
}