11 // ConnTimeout is the amount of time after no packets being received
12 // from a Peer that it is automatically disconnected.
13 ConnTimeout = 30 * time.Second
15 // ConnTimeout is the amount of time after no packets being sent
16 // to a Peer that a CtlPing is automatically sent to prevent timeout.
17 PingTimeout = 5 * time.Second
20 // A Peer is a connection to a client or server.
25 disco chan struct{} // close-only
30 errs chan error // don't close
31 timedout chan struct{} // close-only
33 chans [ChannelCount]pktchan // read/write
42 // Only accessed by Peer.processRawPkt.
43 insplit map[seqnum][][]byte
44 inrel map[seqnum][]byte
47 ackchans sync.Map // map[seqnum]chan struct{}
57 // Conn returns the net.PacketConn used to communicate with the Peer.
58 func (p *Peer) Conn() net.PacketConn { return p.conn }
60 // Addr returns the address of the Peer.
61 func (p *Peer) Addr() net.Addr { return p.addr }
63 // Disco returns a channel that is closed when the Peer is closed.
64 func (p *Peer) Disco() <-chan struct{} { return p.disco }
66 // ID returns the ID of the Peer.
67 func (p *Peer) ID() PeerID { return p.id }
69 // IsSrv reports whether the Peer is a server.
70 func (p *Peer) IsSrv() bool {
71 return p.ID() == PeerIDSrv
74 // TimedOut reports whether the Peer has timed out.
75 func (p *Peer) TimedOut() bool {
84 // Recv recieves a packet from the Peer.
85 // You should keep calling this until it returns net.ErrClosed
86 // so it doesn't leak a goroutine.
87 func (p *Peer) Recv() (Pkt, error) {
89 case pkt, ok := <-p.pkts:
95 return Pkt{}, net.ErrClosed
104 // Close closes the Peer but does not send a disconnect packet.
105 func (p *Peer) Close() error {
125 func newPeer(conn net.PacketConn, addr net.Addr, id, idOfPeer PeerID) *Peer {
132 pkts: make(chan Pkt),
133 disco: make(chan struct{}),
134 errs: make(chan error),
137 for i := range p.chans {
138 p.chans[i] = pktchan{
139 insplit: make(map[seqnum][][]byte),
140 inrel: make(map[seqnum][]byte),
143 outsplitsn: seqnumInit,
144 outrelsn: seqnumInit,
145 outrelwin: seqnumInit,
149 p.timedout = make(chan struct{})
150 p.timeout = time.AfterFunc(ConnTimeout, func() {
157 p.ping = time.NewTicker(PingTimeout)
158 go p.sendPings(p.ping.C)
163 func (p *Peer) sendPings(ping <-chan time.Time) {
164 pkt := rawPkt{Data: []byte{uint8(rawTypeCtl), uint8(ctlPing)}}
169 if _, err := p.sendRaw(pkt); err != nil {
170 p.errs <- fmt.Errorf("can't send ping: %w", err)
178 // Connect connects to the server on conn
179 // and closes conn when the Peer disconnects.
180 func Connect(conn net.PacketConn, addr net.Addr) *Peer {
181 srv := newPeer(conn, addr, PeerIDSrv, PeerIDNil)
183 pkts := make(chan netPkt)
184 go readNetPkts(conn, pkts, srv.errs)
185 go srv.processNetPkts(pkts)