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.

server.rs 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. use std::{
  2. io::{prelude::*, BufReader, Lines},
  3. net::{TcpListener, TcpStream},
  4. };
  5. use std::sync::{Arc, Mutex};
  6. use std::thread::available_parallelism;
  7. use crate::connection_pool::ConnectionPool;
  8. use crate::thread_pool::ThreadPool;
  9. mod thread_pool;
  10. mod connection_pool;
  11. fn main() {
  12. // start server on localhost (for remote access use: 0.0.0.0)
  13. let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
  14. // create thread pool (size = no. of cpu cores)
  15. let pool = ThreadPool::new(available_parallelism().unwrap().get());
  16. //let pool = ThreadPool::new(2);
  17. let conn_pool = Arc::new(Mutex::new(ConnectionPool::new()));
  18. let mut cc: u32 = 0;
  19. // handling function for incoming requests
  20. for stream in listener.incoming() {
  21. let stream = stream.unwrap();
  22. conn_pool.lock().unwrap().add_connection(cc, stream.try_clone().unwrap());
  23. let ccc = cc;
  24. let cconn_pool = conn_pool.clone();
  25. // pass request to thread pool
  26. pool.execute(move || {
  27. handle_connection(stream, ccc, cconn_pool);
  28. });
  29. cc += 1;
  30. }
  31. println!("Shutting down.");
  32. }
  33. fn handle_connection(mut stream: TcpStream, iid: u32, conn_pool: Arc<Mutex<ConnectionPool>>) {
  34. // clone TcpStream for simultaneous receiving and sending
  35. //let mut stream2 = stream.try_clone().unwrap();
  36. // initialize reading buffer (for better performance!)
  37. let buf_reader: BufReader<&mut TcpStream> = BufReader::new(&mut stream);
  38. // request: read received text line by line (continuous until connection closed)
  39. let request: Lines<BufReader<&mut TcpStream>> = buf_reader.lines();
  40. // let request: Bytes<BufReader<&mut TcpStream>> = buf_reader.bytes();
  41. println!("Request: {:#?}", request);
  42. // processing function for every text line received by request (terminates when conn closed)
  43. for elem in request
  44. {
  45. // store received line in variable s
  46. let s = elem.unwrap();
  47. println!("{:?}", s);
  48. conn_pool.lock().unwrap().broadcast(&iid, &s);
  49. // send received line back to sender (append LF)
  50. //stream2.write_all(s.as_bytes()).unwrap();
  51. //stream2.write_all(b"\n").unwrap();
  52. }
  53. }