~fnux/yggdrasil-go-coap

yggdrasil-go-coap/net/yggdrasillistener.go -rw-r--r-- 1.7 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
package net

import (
  "context"
  "fmt"
  "time"
  "net"
  "sync/atomic"
  "github.com/yggdrasil-network/yggdrasil-go/src/yggdrasil"
)

type YggdrasilListener struct {
	listener  *yggdrasil.Listener
	heartBeat time.Duration
	deadline atomic.Value
}

func NewYggdrasilListener(node YggdrasilNode, heartBeat time.Duration) (*YggdrasilListener, error) {
	listener, err := node.Core.ConnListen()
	if err != nil {
		return nil, fmt.Errorf("cannot create new Yggdrasil listener: %v", err)
	}
	return &YggdrasilListener{listener: listener, heartBeat: heartBeat}, nil
}

// AcceptWithContext waits with context for a generic Conn.
func (l *YggdrasilListener) 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
	}
}

// Accept waits for a generic Conn.
func (l *YggdrasilListener) Accept() (net.Conn, error) {
	// TODO: handle deadline.
	return l.AcceptWithContext(context.Background())
}

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

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

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