You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

connection_pool.rs 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. use std::{
  2. sync::{Arc, Mutex},
  3. collections::HashMap,
  4. net::{TcpStream},
  5. io::{Write},
  6. };
  7. pub struct ConnectionPool{
  8. conns: Arc<Mutex<HashMap<u32, TcpStream>>>,
  9. }
  10. impl ConnectionPool{
  11. pub fn new() -> Self {
  12. ConnectionPool{
  13. conns: Arc::new(Mutex::new(HashMap::new())),
  14. }
  15. }
  16. pub fn add_connection(&self, iid: u32, conn: TcpStream) {
  17. self.conns.lock().unwrap().insert(iid, conn);
  18. }
  19. pub fn del_connection(&self, iid: u32) {
  20. self.conns.lock().unwrap().remove(&iid);
  21. }
  22. pub fn unicast(&self, recv_iid: &u32, msg: &String) {
  23. let mut del_conn = false;
  24. match self.conns.lock().unwrap().get(recv_iid) {
  25. Some(mut conn) => {
  26. if conn.write_all(msg.as_bytes()).is_err() {
  27. del_conn = true;
  28. }
  29. },
  30. None => {
  31. println!("Unknown recv_iid: {:#?}", recv_iid);
  32. return;
  33. }
  34. }
  35. if del_conn{
  36. self.del_connection(*recv_iid);
  37. }
  38. }
  39. pub fn broadcast(&self, sender_iid: &u32, msg: &String) {
  40. let mut del_conns: Vec<u32> = Vec::new();
  41. for (iid, mut conn) in self.conns.lock().unwrap().iter() {
  42. if sender_iid.ne(iid){
  43. if conn.write_all(msg.as_bytes()).is_err() {
  44. del_conns.push(*iid);
  45. continue;
  46. }
  47. else if conn.write_all(b"\n").is_err() {
  48. del_conns.push(*iid);
  49. }
  50. }
  51. }
  52. for iid in del_conns {
  53. self.del_connection(iid);
  54. }
  55. }
  56. }