/
net.go
42 lines (38 loc) · 830 Bytes
/
net.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
// Copyright (c) 2012-2013 Toby DiPasquale.
package main
import (
"fmt"
"github.com/codeslinger/log"
"net"
)
type TCPService interface {
SetClientOptions(*net.TCPConn) error
Handle(*net.TCPConn)
Addr() *net.TCPAddr
Shutdown()
}
func RunTCP(t TCPService) {
l, err := net.ListenTCP("tcp", t.Addr())
if err != nil {
log.Error("failed to bind to local address %s", t.Addr())
t.Shutdown()
return
}
defer l.Close()
log.Info("listening for connections on %s", t.Addr())
for {
conn, err := l.AcceptTCP()
if err != nil {
log.Error("failed to accept connection: %v", err)
continue
}
if err := t.SetClientOptions(conn); err != nil {
conn.Close()
continue
}
log.Trace(func() string {
return fmt.Sprintf("%s: client connected to %s", conn.RemoteAddr(), t.Addr())
})
go t.Handle(conn)
}
}