~fnux/yggdrasil-go-coap

yggdrasil-go-coap/net/tcplistener.go -rw-r--r-- 2.1 KiB
614f652bTimothée Floure Add syntax highlighting to code snippets in README 1 year, 8 months ago
                                                                                
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 net

import (
	"context"
	"fmt"
	"net"
	"time"
)

// TCPListener is a TCP network listener that provides accept with context.
type TCPListener struct {
	listener  *net.TCPListener
	heartBeat time.Duration
}

func newNetTCPListen(network string, addr string) (*net.TCPListener, error) {
	a, err := net.ResolveTCPAddr(network, addr)
	if err != nil {
		return nil, fmt.Errorf("cannot create new net tcp listener: %v", err)
	}

	tcp, err := net.ListenTCP(network, a)
	if err != nil {
		return nil, fmt.Errorf("cannot create new net tcp listener: %v", err)
	}
	return tcp, nil
}

// NewTCPListener creates tcp listener.
// Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only).
func NewTCPListener(network string, addr string, heartBeat time.Duration) (*TCPListener, error) {
	tcp, err := newNetTCPListen(network, addr)
	if err != nil {
		return nil, fmt.Errorf("cannot create new tcp listener: %v", err)
	}
	return &TCPListener{listener: tcp, heartBeat: heartBeat}, nil
}

// AcceptContext waits with context for a generic Conn.
func (l *TCPListener) AcceptWithContext(ctx context.Context) (net.Conn, error) {
	for {
		select {
		case <-ctx.Done():
			if ctx.Err() != nil {
				return nil, fmt.Errorf("cannot accept connections: %v", ctx.Err())
			}
			return nil, nil
		default:
		}
		err := l.SetDeadline(time.Now().Add(l.heartBeat))
		if err != nil {
			return nil, fmt.Errorf("cannot accept connections: %v", err)
		}
		rw, err := l.listener.Accept()
		if err != nil {
			if isTemporary(err) {
				continue
			}
			return nil, fmt.Errorf("cannot accept connections: %v", err)
		}
		return rw, nil
	}
}

// SetDeadline sets deadline for accept operation.
func (l *TCPListener) SetDeadline(t time.Time) error {
	return l.listener.SetDeadline(t)
}

// Accept waits for a generic Conn.
func (l *TCPListener) Accept() (net.Conn, error) {
	return l.AcceptWithContext(context.Background())
}

// Close closes the connection.
func (l *TCPListener) Close() error {
	return l.listener.Close()
}

// Addr represents a network end point address.
func (l *TCPListener) Addr() net.Addr {
	return l.listener.Addr()
}