udp.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package udp
  2. import (
  3. "net"
  4. "sync"
  5. "github.com/v2ray/v2ray-core/common/alloc"
  6. v2net "github.com/v2ray/v2ray-core/common/net"
  7. )
  8. type UDPPayloadHandler func(*alloc.Buffer, v2net.Destination)
  9. type UDPHub struct {
  10. sync.RWMutex
  11. conn *net.UDPConn
  12. callback UDPPayloadHandler
  13. accepting bool
  14. }
  15. func ListenUDP(address v2net.Address, port v2net.Port, callback UDPPayloadHandler) (*UDPHub, error) {
  16. udpConn, err := net.ListenUDP("udp", &net.UDPAddr{
  17. IP: address.IP(),
  18. Port: int(port),
  19. })
  20. if err != nil {
  21. return nil, err
  22. }
  23. hub := &UDPHub{
  24. conn: udpConn,
  25. callback: callback,
  26. }
  27. go hub.start()
  28. return hub, nil
  29. }
  30. func (this *UDPHub) Close() {
  31. this.Lock()
  32. defer this.Unlock()
  33. this.accepting = false
  34. this.conn.Close()
  35. }
  36. func (this *UDPHub) WriteTo(payload []byte, dest v2net.Destination) (int, error) {
  37. return this.conn.WriteToUDP(payload, &net.UDPAddr{
  38. IP: dest.Address().IP(),
  39. Port: int(dest.Port()),
  40. })
  41. }
  42. func (this *UDPHub) start() {
  43. this.Lock()
  44. this.accepting = true
  45. this.Unlock()
  46. for this.Running() {
  47. buffer := alloc.NewBuffer()
  48. nBytes, addr, err := this.conn.ReadFromUDP(buffer.Value)
  49. if err != nil {
  50. buffer.Release()
  51. continue
  52. }
  53. buffer.Slice(0, nBytes)
  54. dest := v2net.UDPDestination(v2net.IPAddress(addr.IP), v2net.Port(addr.Port))
  55. go this.callback(buffer, dest)
  56. }
  57. }
  58. func (this *UDPHub) Running() bool {
  59. this.RLock()
  60. defer this.RUnlock()
  61. return this.accepting
  62. }