1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
use crate::message_table::{MsgTableParts, CONNECTION_TYPE_MID, DISCONNECT_TYPE_MID, RESPONSE_TYPE_MID};
use crate::net::{CId, CIdSpec, Config, DeserFn, ErasedNetMsg, NetMsg, Status, Transport};
use crate::tcp::TcpCon;
use crate::udp::UdpCon;
use crate::MId;
use hashbrown::HashMap;
use log::{debug, error, trace};
use std::any::{type_name, Any, TypeId};
use std::collections::VecDeque;
use std::io;
use std::io::ErrorKind::{InvalidData, WouldBlock};
use std::io::{Error, ErrorKind};
use std::net::{SocketAddr, TcpListener};
use std::time::{Duration, Instant};

/// A server.
///
/// Listens on a address and port, allowing for clients to connect. Newly connected clients will
/// be given a client ID (CId) starting at `1` that is unique for the session.
///
/// This will manage multiple connections to clients. Each connection will have a TCP and UDP
/// connection on the same address and port.
pub struct Server {
    /// The current cid. incremented then assigned to new connections.
    current_cid: CId,
    /// The configuration of the server.
    config: Config,
    /// The received message buffer.
    ///
    /// Each [`MId`] has its own vector.
    msg_buff: Vec<Vec<ErasedNetMsg>>,

    /// The pending connections (Connections that are established but have
    /// not sent a connection message yet).
    new_cons: Vec<(TcpCon, CId, Instant)>,
    /// Disconnected connections.
    disconnected: VecDeque<(CId, Status)>,
    /// The listener for new connections.
    listener: TcpListener,
    /// The TCP connection for this client.
    tcp: HashMap<CId, TcpCon>,
    /// The UDP connection for this client.
    udp: UdpCon,

    /// The map from CId to SocketAddr for the UDP messages to be sent to.
    ///
    /// This needs to be a mirror of `addr_cid`, and needs to be added and removed with the TCP
    /// connections. Because of these things, ***ALWAYS*** use the `add_tcp_con` and `rm_tcp_con`
    /// functions to mutate these maps.
    cid_addr: HashMap<CId, SocketAddr>,
    /// The map from SocketAddr to CId for the UDP messages to be sent to.
    ///
    /// This needs to be a mirror of `cid_addr`, and needs to be added and removed with the TCP
    /// connections. Because of these things, ***ALWAYS*** use the `add_tcp_con` and `rm_tcp_con`
    /// functions to mutate these maps.
    addr_cid: HashMap<SocketAddr, CId>,

    /// The [`MsgTableParts`] to use for sending messages.
    parts: MsgTableParts,
}

impl Server {
    /// Creates a new [`Server`].
    ///
    /// Creates a new [`Server`] listening on the address `listen_addr`.
    pub fn new(
        mut listen_addr: SocketAddr,
        parts: MsgTableParts,
        config: Config,
    ) -> io::Result<Self> {
        let listener = TcpListener::bind(listen_addr)?;
        listen_addr = listener.local_addr().unwrap();
        listener.set_nonblocking(true)?;
        let udp = UdpCon::new(listen_addr, None, config.max_msg_size)?;

        debug!("New server created at {}.", listen_addr);

        let mid_count = parts.tid_map.len();
        let mut msg_buff = Vec::with_capacity(mid_count);
        for _i in 0..mid_count {
            msg_buff.push(vec![]);
        }

        Ok(Server {
            current_cid: 0,
            config,
            msg_buff,
            new_cons: vec![],
            disconnected: VecDeque::new(),
            listener,
            tcp: HashMap::new(),
            udp,
            cid_addr: Default::default(),
            addr_cid: Default::default(),
            parts,
        })
    }

    /// Gets the config of the server.
    pub fn config(&self) -> &Config {
        &self.config
    }

    /// Disconnects from the given `cid`. You should always disconnect all clients before dropping
    /// the server to let the clients know that you intentionally disconnected. The `discon_msg`
    /// allows you to give a reason for the disconnect.
    pub fn disconnect<T: Any + Send + Sync>(&mut self, discon_msg: &T, cid: CId) -> io::Result<()> {
        if !self.alive(cid) {
            return Err(io::Error::new(ErrorKind::InvalidData, "Invalid CId."));
        }
        debug!("Disconnecting CId {}", cid);
        self.send_to(cid, discon_msg)?;
        // Close the TcpCon
        self.tcp.get_mut(&cid).unwrap().close()?;
        // No shutdown method on udp.
        self.disconnected.push_back((cid, Status::Closed));
        Ok(())
    }

    /// Handles all available new connection attempts in a loop, calling the given hook for each.
    ///
    /// The hook function should return `(should_accept, response_msg)`.
    ///
    /// Types `C` and `R` need to match the `C` and `R` types that you passed into
    /// [`MsgTable::build()`](MsgTable::build).
    ///
    /// Returns whether a connection was handled.
    pub fn handle_new_con<C: Any + Send + Sync, R: Any + Send + Sync>(
        &mut self,
        mut hook: impl FnMut(CId, C) -> (bool, R),
    ) -> bool {
        // Start handling incoming connections.
        self.start_incoming();

        // If we have no active connections, we don't have to continue.
        if self.new_cons.len() == 0 { return false; }

        // Handle the new connections.
        let deser_fn = self.parts.deser[CONNECTION_TYPE_MID];

        // List of accepted connections.
        let mut accepted = vec![];
        // List of rejected connections.
        let mut rejected = vec![];
        // List of connections that errored out.
        let mut dead = vec![];

        for (idx, (con, cid, time)) in self.new_cons.iter_mut().enumerate() {
            match Self::handle_con_helper::<C>(deser_fn, con, self.config.timeout, time) {
                // Done connecting.
                Ok(c) => {
                    // Call hook
                    let (acc, resp) = hook(*cid, c);
                    if acc {
                        accepted.push((idx, resp));
                    } else {
                        rejected.push((idx, resp));
                    }
                    break; // Only handle 1 connection max.
                }
                // Not done yet.
                Err(e) if e.kind() == ErrorKind::WouldBlock => {}
                // Error in connecting.
                Err(e) => {
                    error!("IO error occurred while handling a pending connection. {}", e);
                    dead.push(idx);
                }
            }
        }

        // Dead connections do not count as handled; they do not call the hook.
        let handled = accepted.len() > 0 || rejected.len() > 0;

        // Handle accepted.
        for (idx, resp) in accepted {
            let (con, cid, _) = self.new_cons.remove(idx);
            self.accept_incoming(cid, con, &resp);
        }

        // Handle rejected.
        for (idx, resp) in rejected {
            let (con, cid, _) = self.new_cons.remove(idx);
            self.reject_incoming(cid, con, &resp);
        }

        // Handle dead.
        for idx in dead {
            self.new_cons.remove(idx);
        }

        handled
    }

    /// Handles all available new connection attempts in a loop, calling the given hook for each.
    ///
    /// The hook function should return `(should_accept, response_msg)`.
    ///
    /// Types `C` and `R` need to match the `C` and `R` types that you passed into
    /// [`MsgTable::build()`](MsgTable::build).
    ///
    /// Returns the number of handled connections.
    pub fn handle_new_cons<C: Any + Send + Sync, R: Any + Send + Sync>(
        &mut self,
        mut hook: impl FnMut(CId, C) -> (bool, R),
    ) -> u32 {
        // Start handling incoming connections.
        self.start_incoming();

        // If we have no active connections, we don't have to continue.
        if self.new_cons.len() == 0 { return 0; }

        // Handle the new connections.
        let deser_fn = self.parts.deser[CONNECTION_TYPE_MID];

        // List of accepted connections.
        let mut accepted = vec![];
        // List of rejected connections.
        let mut rejected = vec![];
        // List of connections that errored out.
        let mut dead = vec![];

        for (idx, (con, cid, time)) in self.new_cons.iter_mut().enumerate() {
            match Self::handle_con_helper::<C>(deser_fn, con, self.config.timeout, time) {
                // Done connecting.
                Ok(c) => {
                    // Call hook
                    let (acc, resp) = hook(*cid, c);
                    if acc {
                        accepted.push((idx, resp));
                    } else {
                        rejected.push((idx, resp));
                    }
                }
                // Not done yet.
                Err(e) if e.kind() == ErrorKind::WouldBlock => {}
                // Error in connecting.
                Err(e) => {
                    error!("IO error occurred while handling a pending connection. {}", e);
                    dead.push(idx);
                }
            }
        }

        // Dead connections do not count as handled; they do not call the hook.
        let handled = accepted.len() + rejected.len();

        // Handle accepted.
        for (idx, resp) in accepted {
            let (con, cid, _) = self.new_cons.remove(idx);
            self.accept_incoming(cid, con, &resp);
        }

        // Handle rejected.
        for (idx, resp) in rejected {
            let (con, cid, _) = self.new_cons.remove(idx);
            self.reject_incoming(cid, con, &resp);
        }

        // Handle dead.
        for idx in dead {
            self.new_cons.remove(idx);
        }

        handled as u32
    }

    /// Encapsulates new connection handling logic by trying to read the connection message.
    ///
    /// If there is an error in connection (including timeout) this will return `Err(e)`. If the
    /// connection opened successfully, it will return `Ok(c)`.
    ///
    /// If this returns an error other than a `WouldBlock` error, it should be removed from the
    /// list of pending connections. If it returns `Ok(c)` it should also be removed, as it has
    /// finished connecting successfully.
    fn handle_con_helper<C: Any + Send + Sync>(
        deser_fn: DeserFn,
        con: &mut TcpCon,
        timeout: Duration,
        time: &Instant,
    ) -> io::Result<C> {
        if time.elapsed() > timeout {
            return Err(Error::new(
                ErrorKind::TimedOut,
                "The new connection did not send a connection message in time.",
            ));
        }

        let (mid, msg) = con.recv()?;

        if mid != CONNECTION_TYPE_MID {
            let e_msg = format!("Expected MId {}, got MId {}.", CONNECTION_TYPE_MID, mid);
            return Err(Error::new(ErrorKind::InvalidData, e_msg));
        }

        let con_msg = deser_fn(msg).map_err(|o| {
            Error::new(
                ErrorKind::InvalidData,
                format!("Encountered a deserialization error when handling a new connection. {}", o),
            )
        })?;

        let con_msg = *con_msg.downcast::<C>().unwrap();
        Ok(con_msg)
    }

    /// Helper function that start handling the incoming tcp connections.
    fn start_incoming(&mut self,) {
        while self.new_cons.len() < self.config.max_con_handle {
            if let Ok((stream, _addr)) = self.listener.accept() {
                debug!("New connection attempt.");
                stream.set_nonblocking(true).unwrap();
                let tcp_con = TcpCon::from_stream(stream, self.config.max_msg_size);
                let cid = self.new_cid();
                self.new_cons.push((tcp_con, cid, Instant::now()));
            } else {
                break;
            }
        }
    }

    /// A helper function that accepts the incoming connection.
    fn accept_incoming<R: Any + Send + Sync>(
        &mut self,
        cid: CId,
        con: TcpCon,
        resp: &R,
    ) {
        let addr = con.peer_addr().unwrap();
        self.add_tcp_con_cid(cid, con);
        if let Err(e) = self.send_to(cid, resp) {
            error!("IO error occurred while responding to a pending connection. {} at {}", e, addr);
        } else {
            debug!("Accepted new connection {} at {}.", cid, addr);
        }
    }

    /// A helper function that rejects the incoming connection.
    fn reject_incoming<R: Any + Send + Sync>(
        &self,
        cid: CId,
        con: TcpCon,
        resp: &R,
    ) {
        // Get items necessary to send.
        let ser = self.parts.ser[RESPONSE_TYPE_MID];
        let payload = match ser(resp) {
            Ok(p) => p,
            Err(e) => {
                error!("{}", e);
                return;
            },
        };

        // Send.
        let addr = con.peer_addr().unwrap();
        if let Err(e) = con.send(RESPONSE_TYPE_MID, &payload) {
            error!("IO error occurred while responding to a pending connection. {} at {}", e, addr);
        } else {
            debug!("Rejected new connection {} at {}.", cid, addr);
        }
    }

    /// Handles a single disconnect, if there is one available to handle.
    ///
    /// If there is no disconnects to handle, `hook` will not be called.
    ///
    /// Returns weather it handled a disconnect.
    pub fn handle_disconnect(&mut self, mut hook: impl FnMut(CId, Status)) -> bool {
        while let Some((cid, status)) = self.disconnected.pop_front() {
            // If the disconnect is a live connection
            if !self.alive(cid) { continue; }

            // call hook.
            hook(cid, status);
            debug!("Removing CId {}", cid);
            self.rm_tcp_con(cid).unwrap();
            return true;
        }
        false
    }

    /// Handles all remaining disconnects.
    ///
    /// Returns the number of disconnects handled.
    pub fn handle_disconnects(&mut self, mut hook: impl FnMut(CId, Status)) -> u32 {
        // disconnect counts.
        let mut i = 0;

        while let Some((cid, status)) = self.disconnected.pop_front() {
            // If the disconnect is a live connection
            if !self.alive(cid) { continue; }

            // call hook.
            hook(cid, status);
            debug!("Removing CId {}", cid);
            self.rm_tcp_con(cid).unwrap();
            i += 1;
        }

        i
    }

    /// A function that encapsulates the sending logic for the TCP transport.
    fn send_tcp(&self, cid: CId, mid: MId, payload: &[u8]) -> io::Result<()> {
        let tcp = match self.tcp.get(&cid) {
            Some(tcp) => tcp,
            None => return Err(Error::new(ErrorKind::InvalidData, "Invalid CId.")),
        };

        tcp.send(mid, payload)
    }

    /// A function that encapsulates the sending logic for the UDP transport.
    fn send_udp(&self, cid: CId, mid: MId, payload: &[u8]) -> io::Result<()> {
        let addr = match self.cid_addr.get(&cid) {
            Some(addr) => *addr,
            None => return Err(Error::new(ErrorKind::InvalidData, "Invalid CId.")),
        };

        self.udp.send_to(addr, mid, payload)
    }

    /// A function that encapsulates the receiving logic for the TCP transport.
    ///
    /// Any errors in receiving are returned. An error of type [`WouldBlock`] means no more
    /// messages can be yielded without blocking.
    fn recv_tcp(&mut self, cid: CId) -> io::Result<(MId, ErasedNetMsg)> {
        let tcp = match self.tcp.get_mut(&cid) {
            Some(tcp) => tcp,
            None => return Err(Error::new(ErrorKind::InvalidData, "Invalid CId.")),
        };

        let (mid, bytes) = tcp.recv()?;

        if !self.parts.valid_mid(mid) {
            let e_msg = format!(
                "TCP: Got a message specifying MId {}, but the maximum MId is {}.",
                mid,
                self.parts.mid_count()
            );
            return Err(Error::new(ErrorKind::InvalidData, e_msg));
        }

        let deser_fn = self.parts.deser[mid];
        let msg = deser_fn(bytes)?;

        let net_msg = ErasedNetMsg {
            cid,
            time: None,
            msg,
        };

        Ok((mid, net_msg))
    }

    /// A function that encapsulates the receiving logic for the `UDP` transport.
    ///
    /// Any errors in receiving are returned. An error of type [`WouldBlock`] means no more
    /// messages can be yielded without blocking. [`InvalidData`] likely means carrier-pigeon
    /// got bad data.
    fn recv_udp(&mut self) -> io::Result<(MId, ErasedNetMsg)> {
        let (from, mid, time, bytes) = self.udp.recv_from()?;

        if !self.parts.valid_mid(mid) {
            let e_msg = format!(
                "TCP: Got a message specifying MId {}, but the maximum MId is {}.",
                mid,
                self.parts.mid_count()
            );
            return Err(Error::new(ErrorKind::InvalidData, e_msg));
        }

        let deser_fn = self.parts.deser[mid];
        let msg = deser_fn(bytes)?;

        let cid = match self.addr_cid.get(&from) {
            Some(&cid) if self.alive(cid) => cid,
            _ => {
                return Err(Error::new(
                    ErrorKind::Other,
                    "Received data from a address that is not connected.",
                ))
            }
        };

        let net_msg = ErasedNetMsg {
            cid,
            time: Some(time),
            msg,
        };

        Ok((mid, net_msg))
    }

    /// Sends a message to the [`CId`] `cid`.
    pub fn send_to<T: Any + Send + Sync>(&self, cid: CId, msg: &T) -> io::Result<()> {
        let tid = TypeId::of::<T>();
        if !self.valid_tid(tid) {
            return Err(io::Error::new(
                ErrorKind::InvalidData,
                "Type not registered.",
            ));
        }
        let mid = self.parts.tid_map[&tid];
        let transport = self.parts.transports[mid];
        let ser_fn = self.parts.ser[mid];
        let b = ser_fn(msg)?;

        trace!(
            "Sending message of MId {}, len {}, to CId {}",
            mid,
            b.len(),
            cid
        );
        match transport {
            Transport::TCP => self.send_tcp(cid, mid, &b[..]),
            Transport::UDP => self.send_udp(cid, mid, &b[..]),
        }?;

        Ok(())
    }

    /// Broadcasts a message to all connected clients.
    pub fn broadcast<T: Any + Send + Sync>(&self, msg: &T) -> io::Result<()> {
        for cid in self.cids() {
            self.send_to(cid, msg)?;
        }
        Ok(())
    }

    /// Sends a message to all [`CId`]s that match `spec`.
    pub fn send_spec<T: Any + Send + Sync>(&self, spec: CIdSpec, msg: &T) -> io::Result<()> {
        for cid in self.cids().filter(|cid| spec.matches(*cid)) {
            self.send_to(cid, msg)?;
        }
        Ok(())
    }

    /// Gets an iterator for the messages of type `T`.
    ///
    /// Make sure to call [`recv_msgs()`](Self::recv_msgs) before calling this.
    ///
    /// ### Panics
    /// Panics if the type `T` was not registered.
    /// For a non-panicking version, see [try_recv()](Self::try_recv).
    pub fn recv<'s, T: Any + Send + Sync>(&'s self) -> impl Iterator<Item = NetMsg<T>> + 's {
        let tid = TypeId::of::<T>();
        if !self.parts.valid_tid(tid) {
            panic!("Type ({}) not registered.", type_name::<T>());
        }
        let mid = self.parts.tid_map[&tid];

        self.msg_buff[mid]
            .iter()
            .map(|m| m.to_typed::<T>().unwrap())
    }

    /// Gets an iterator for the messages of type `T`.
    ///
    /// Make sure to call [`recv_msgs()`](Self::recv_msgs) before calling this.
    ///
    /// Returns `None` if the type `T` was not registered.
    pub fn try_recv<'s, T: Any + Send + Sync>(
        &'s self,
    ) -> Option<impl Iterator<Item = NetMsg<T>> + 's> {
        let tid = TypeId::of::<T>();
        let mid = *self.parts.tid_map.get(&tid)?;

        Some(
            self.msg_buff[mid]
                .iter()
                .map(|m| m.to_typed::<T>().unwrap()),
        )
    }

    /// Gets an iterator for the messages of type `T` that have been received from [`CId`]s that
    /// match `spec`.
    ///
    /// Make sure to call [`recv_msgs()`](Self::recv_msgs)
    ///
    /// ### Panics
    /// Panics if the type `T` was not registered.
    /// For a non-panicking version, see [try_recv_spec()](Self::try_recv_spec).
    pub fn recv_spec<T: Any + Send + Sync>(
        &self,
        spec: CIdSpec,
    ) -> impl Iterator<Item = NetMsg<T>> + '_ {
        let tid = TypeId::of::<T>();
        if !self.parts.valid_tid(tid) {
            panic!("Type ({}) not registered.", type_name::<T>());
        }
        let mid = self.parts.tid_map[&tid];

        self.msg_buff[mid]
            .iter()
            .filter(move |net_msg| spec.matches(net_msg.cid))
            .map(|net_msg| net_msg.to_typed().unwrap())
    }

    /// Gets an iterator for the messages of type `T` that have been received from [`CId`]s that
    /// match `spec`.
    ///
    /// Make sure to call [`recv_msgs()`](Self::recv_msgs)
    ///
    /// Returns `None` if the type `T` was not registered.
    pub fn try_recv_spec<T: Any + Send + Sync>(
        &self,
        spec: CIdSpec,
    ) -> Option<impl Iterator<Item = NetMsg<T>> + '_> {
        let tid = TypeId::of::<T>();
        let mid = *self.parts.tid_map.get(&tid)?;

        Some(
            self.msg_buff[mid]
                .iter()
                .filter(move |net_msg| spec.matches(net_msg.cid))
                .map(|net_msg| net_msg.to_typed().unwrap()),
        )
    }

    /// Receives the messages from the connections. This should be done before calling `recv<T>()`.
    ///
    /// When done in a game loop, you should call `clear_msgs()`, then `recv_msgs()` before default
    /// time. This will clear the messages between frames.
    pub fn recv_msgs(&mut self) -> u32 {
        let mut i = 0;

        // TCP
        for cid in self.cids().collect::<Vec<_>>() {
            loop {
                let msg = self.recv_tcp(cid);
                if self.handle_tcp_msg(&mut i, cid, msg) {
                    // Done yielding messages.
                    break;
                }
            }
        }

        // UDP
        loop {
            let msg = self.recv_udp();
            if self.handle_udp_msg(&mut i, msg) {
                // Done yielding messages.
                break;
            }
        }
        i
    }

    /// Logic for handling a new `TCP` message.
    ///
    /// Increments `count` when it successfully got a message including a disconnect message.
    ///
    /// When getting an error, this will disconnect the peer. When getting a disconnection message,
    /// this will add it to the disconnection que. Otherwise it adds it to the msg buffer.
    ///
    /// returns weather the tcp connection is done yielding messages.
    fn handle_tcp_msg(
        &mut self,
        count: &mut u32,
        cid: CId,
        msg: io::Result<(MId, ErasedNetMsg)>,
    ) -> bool {
        match msg {
            Err(e) if e.kind() == WouldBlock => true,
            // Other error occurred.
            Err(e) => {
                error!(
                    "TCP({}): IO error occurred while receiving data. {}",
                    cid, e
                );
                self.disconnected.push_back((cid, Status::Dropped(e)));
                true
            }
            // Got a message.
            Ok((mid, net_msg)) => {
                *count += 1;
                if mid == DISCONNECT_TYPE_MID {
                    debug!("Disconnecting peer {}", cid);
                    self.disconnected
                        .push_back((cid, Status::Disconnected(net_msg.msg)));
                    return true;
                }

                self.msg_buff[mid].push(net_msg);
                false
            }
        }
    }

    /// Logic for handling a new `UDP` message.
    ///
    /// Increments `count` when it successfully got a message
    ///
    /// When getting an error, this will log and ignore it. Otherwise it adds it to the msg buffer.
    ///
    /// returns weather the udp connection is done yielding messages.
    fn handle_udp_msg(&mut self, count: &mut u32, msg: io::Result<(MId, ErasedNetMsg)>) -> bool {
        match msg {
            Err(e) if e.kind() == WouldBlock => true,
            // Other error occurred.
            Err(e) => {
                error!("UDP: IO error occurred while receiving data. {}", e);
                true
            }
            // Got a message.
            Ok((mid, net_msg)) => {
                *count += 1;
                self.msg_buff[mid].push(net_msg);
                false
            }
        }
    }

    /// Clears messages from the buffer.
    pub fn clear_msgs(&mut self) {
        for buff in self.msg_buff.iter_mut() {
            buff.clear();
        }
    }

    /// Gets the address that the server is listening on.
    pub fn listen_addr(&self) -> SocketAddr {
        self.listener.local_addr().unwrap()
    }

    /// An iterator of the [`CId`]s.
    pub fn cids(&self) -> impl Iterator<Item = CId> + '_ {
        self.cid_addr.keys().map(|cid| *cid)
    }

    /// Returns whether the connection of the given [`CId`] is alive.
    pub fn alive(&self, cid: CId) -> bool {
        self.cid_addr.contains_key(&cid)
    }

    /// Returns whether a message of type `tid` can be sent.
    pub fn valid_tid(&self, tid: TypeId) -> bool {
        self.parts.valid_tid(tid)
    }

    /// The number of active connections. To ensure an accurate count, it is best to call this
    /// after calling [`handle_disconnects()`](Self::handle_disconnects).
    pub fn connection_count(&self) -> usize {
        self.cid_addr.len()
    }

    /// Gets the address of the given [`CId`].
    pub fn addr_of(&self, cid: CId) -> Option<SocketAddr> {
        self.cid_addr.get(&cid).map(|o| *o)
    }

    /// Gets the address of the given [`CId`].
    pub fn cid_of(&self, addr: SocketAddr) -> Option<CId> {
        self.addr_cid.get(&addr).map(|o| *o)
    }

    // Private:
    fn new_cid(&mut self) -> CId {
        self.current_cid += 1;
        self.current_cid
    }

    /// Adds a `TCP` connection with the [`CId`] `cid`. The cid needs to be unique, generate one
    /// with `new_cid()`.
    fn add_tcp_con_cid(&mut self, cid: CId, con: TcpCon) {
        let peer_addr = con.peer_addr().unwrap();
        self.tcp.insert(cid, con);
        self.addr_cid.insert(peer_addr, cid);
        self.cid_addr.insert(cid, peer_addr);
    }

    /// Removes a `TCP` connection.
    fn rm_tcp_con(&mut self, cid: CId) -> io::Result<()> {
        self.tcp
            .remove(&cid)
            .ok_or(Error::new(InvalidData, "Invalid CId."))?;
        let addr = self.cid_addr.remove(&cid).unwrap();
        self.addr_cid.remove(&addr);
        Ok(())
    }
}