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.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. let mut msg1: String;
  42. msg1 = format!("User {sender_iid}: ").parse().unwrap();
  43. msg1.push_str(msg);
  44. for (iid, mut conn) in self.conns.lock().unwrap().iter() {
  45. if sender_iid.ne(iid){
  46. if conn.write_all(msg1.as_bytes()).is_err() {
  47. del_conns.push(*iid);
  48. continue;
  49. }
  50. else if conn.write_all(b"\n").is_err() {
  51. del_conns.push(*iid);
  52. }
  53. }
  54. }
  55. for iid in del_conns {
  56. self.del_connection(iid);
  57. }
  58. }
  59. }