utp_util.go 1.74 KB
Newer Older
Jeromy's avatar
Jeromy committed
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
package utp

import (
	"errors"
	"net"
	"time"

	utp "QmVBEPpwYNGb5xQW6jPzYgV86KSPRrzhe4hA7o7mtAHZsT/go-utp"
)

type Listener struct {
	*utp.Socket
}

type Conn struct {
	net.Conn
}

type Addr struct {
	net   string
	child net.Addr
}

func (ca *Addr) Network() string {
	return ca.net
}

func (ca *Addr) String() string {
	return ca.child.String()
}

func (ca *Addr) Child() net.Addr {
	return ca.child
}

func MakeAddr(a net.Addr) net.Addr {
	return &Addr{
		net:   "utp",
		child: a,
	}
}

func ResolveAddr(network string, host string) (net.Addr, error) {
	a, err := net.ResolveUDPAddr("udp"+network[3:], host)
	if err != nil {
		return nil, err
	}

	return MakeAddr(a), nil
}

func (u *Conn) LocalAddr() net.Addr {
	return MakeAddr(u.Conn.LocalAddr())
}

func (u *Conn) RemoteAddr() net.Addr {
	return MakeAddr(u.Conn.RemoteAddr())
}

func Listen(network string, laddr string) (net.Listener, error) {
	switch network {
	case "utp", "utp4", "utp6":
		s, err := utp.NewSocket("udp"+network[3:], laddr)
		if err != nil {
			return nil, err
		}

		return &Listener{s}, nil

	default:
		return nil, errors.New("unrecognized network: " + network)
	}
}

func (u *Listener) Accept() (net.Conn, error) {
	c, err := u.Socket.Accept()
	if err != nil {
		return nil, err
	}

	return &Conn{c}, nil
}

func (u *Listener) Addr() net.Addr {
	return MakeAddr(u.Socket.Addr())
}

type Dialer struct {
	Timeout   time.Duration
	LocalAddr net.Addr
}

func (d *Dialer) Dial(rnet string, raddr string) (net.Conn, error) {
	if d.LocalAddr != nil {
		s, err := utp.NewSocket(d.LocalAddr.Network(), d.LocalAddr.String())
		if err != nil {
			return nil, err
		}

		// zero timeout is the same as calling s.Dial()
		return s.DialTimeout(raddr, d.Timeout)
	}

	return utp.DialTimeout(raddr, d.Timeout)
}