v2ray-core/transport/internet/udp/udp.go

75 lines
1.4 KiB
Go
Raw Normal View History

2016-06-14 20:54:08 +00:00
package udp
2016-01-28 16:43:47 +00:00
import (
"net"
2016-07-13 19:39:18 +00:00
"sync"
2016-01-28 16:43:47 +00:00
"github.com/v2ray/v2ray-core/common/alloc"
v2net "github.com/v2ray/v2ray-core/common/net"
)
type UDPPayloadHandler func(*alloc.Buffer, v2net.Destination)
type UDPHub struct {
2016-07-13 19:39:18 +00:00
sync.RWMutex
2016-01-28 16:43:47 +00:00
conn *net.UDPConn
callback UDPPayloadHandler
accepting bool
}
2016-05-29 14:37:52 +00:00
func ListenUDP(address v2net.Address, port v2net.Port, callback UDPPayloadHandler) (*UDPHub, error) {
2016-01-28 16:43:47 +00:00
udpConn, err := net.ListenUDP("udp", &net.UDPAddr{
2016-05-29 14:37:52 +00:00
IP: address.IP(),
2016-01-28 16:43:47 +00:00
Port: int(port),
})
if err != nil {
return nil, err
}
hub := &UDPHub{
conn: udpConn,
callback: callback,
}
go hub.start()
return hub, nil
}
func (this *UDPHub) Close() {
2016-07-13 19:39:18 +00:00
this.Lock()
defer this.Unlock()
2016-01-28 16:43:47 +00:00
this.accepting = false
this.conn.Close()
}
func (this *UDPHub) WriteTo(payload []byte, dest v2net.Destination) (int, error) {
return this.conn.WriteToUDP(payload, &net.UDPAddr{
IP: dest.Address().IP(),
Port: int(dest.Port()),
})
}
func (this *UDPHub) start() {
2016-07-13 19:39:18 +00:00
this.Lock()
2016-01-29 13:39:55 +00:00
this.accepting = true
2016-07-13 19:39:18 +00:00
this.Unlock()
for this.Running() {
2016-01-28 16:43:47 +00:00
buffer := alloc.NewBuffer()
nBytes, addr, err := this.conn.ReadFromUDP(buffer.Value)
if err != nil {
buffer.Release()
continue
}
buffer.Slice(0, nBytes)
dest := v2net.UDPDestination(v2net.IPAddress(addr.IP), v2net.Port(addr.Port))
go this.callback(buffer, dest)
}
}
2016-07-13 19:39:18 +00:00
func (this *UDPHub) Running() bool {
this.RLock()
defer this.RUnlock()
return this.accepting
}