github.com/pion/webrtc/v4@v4.0.1/internal/mux/endpoint.go (about) 1 // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly> 2 // SPDX-License-Identifier: MIT 3 4 package mux 5 6 import ( 7 "errors" 8 "io" 9 "net" 10 "time" 11 12 "github.com/pion/ice/v4" 13 "github.com/pion/transport/v3/packetio" 14 ) 15 16 // Endpoint implements net.Conn. It is used to read muxed packets. 17 type Endpoint struct { 18 mux *Mux 19 buffer *packetio.Buffer 20 onClose func() 21 } 22 23 // Close unregisters the endpoint from the Mux 24 func (e *Endpoint) Close() (err error) { 25 if e.onClose != nil { 26 e.onClose() 27 } 28 29 if err = e.close(); err != nil { 30 return err 31 } 32 33 e.mux.RemoveEndpoint(e) 34 return nil 35 } 36 37 func (e *Endpoint) close() error { 38 return e.buffer.Close() 39 } 40 41 // Read reads a packet of len(p) bytes from the underlying conn 42 // that are matched by the associated MuxFunc 43 func (e *Endpoint) Read(p []byte) (int, error) { 44 return e.buffer.Read(p) 45 } 46 47 // ReadFrom reads a packet of len(p) bytes from the underlying conn 48 // that are matched by the associated MuxFunc 49 func (e *Endpoint) ReadFrom(p []byte) (int, net.Addr, error) { 50 i, err := e.Read(p) 51 return i, nil, err 52 } 53 54 // Write writes len(p) bytes to the underlying conn 55 func (e *Endpoint) Write(p []byte) (int, error) { 56 n, err := e.mux.nextConn.Write(p) 57 if errors.Is(err, ice.ErrNoCandidatePairs) { 58 return 0, nil 59 } else if errors.Is(err, ice.ErrClosed) { 60 return 0, io.ErrClosedPipe 61 } 62 63 return n, err 64 } 65 66 // WriteTo writes len(p) bytes to the underlying conn 67 func (e *Endpoint) WriteTo(p []byte, _ net.Addr) (int, error) { 68 return e.Write(p) 69 } 70 71 // LocalAddr is a stub 72 func (e *Endpoint) LocalAddr() net.Addr { 73 return e.mux.nextConn.LocalAddr() 74 } 75 76 // RemoteAddr is a stub 77 func (e *Endpoint) RemoteAddr() net.Addr { 78 return e.mux.nextConn.RemoteAddr() 79 } 80 81 // SetDeadline is a stub 82 func (e *Endpoint) SetDeadline(time.Time) error { 83 return nil 84 } 85 86 // SetReadDeadline is a stub 87 func (e *Endpoint) SetReadDeadline(time.Time) error { 88 return nil 89 } 90 91 // SetWriteDeadline is a stub 92 func (e *Endpoint) SetWriteDeadline(time.Time) error { 93 return nil 94 } 95 96 // SetOnClose is a user set callback that 97 // will be executed when `Close` is called 98 func (e *Endpoint) SetOnClose(onClose func()) { 99 e.onClose = onClose 100 }