]> git.lizzy.rs Git - mt.git/blob - rudp/net.go
421a3e73ec9254147dbfb161fb3b30d627281120
[mt.git] / rudp / net.go
1 package rudp
2
3 import (
4         "errors"
5         "net"
6         "strings"
7 )
8
9 // TODO: Use net.ErrClosed when Go 1.16 is released.
10 var ErrClosed = errors.New("use of closed peer")
11
12 /*
13 netPkt.Data format (big endian):
14
15         ProtoID
16         Src PeerID
17         ChNo uint8 // Must be < ChannelCount.
18         RawPkt.Data
19 */
20 type netPkt struct {
21         SrcAddr net.Addr
22         Data    []byte
23 }
24
25 func readNetPkts(conn net.PacketConn, pkts chan<- netPkt, errs chan<- error) {
26         for {
27                 buf := make([]byte, MaxNetPktSize)
28                 n, addr, err := conn.ReadFrom(buf)
29                 if err != nil {
30                         // TODO: Change to this when Go 1.16 is released:
31                         // if errors.Is(err, net.ErrClosed) {
32                         if strings.Contains(err.Error(), "use of closed network connection") {
33                                 break
34                         }
35
36                         errs <- err
37                         continue
38                 }
39
40                 pkts <- netPkt{addr, buf[:n]}
41         }
42
43         close(pkts)
44 }