Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. use std::io::prelude::*;
  2. use std::thread;
  3. use std::net::{TcpStream, TcpListener};
  4.  
  5. fn network_process() {
  6. let listener = TcpListener::bind("127.0.0.1:1337").unwrap();
  7. let mut handlers = Vec::new();
  8.  
  9. match listener.accept() {
  10. Ok((mut socket, addr)) => {
  11. println!("new client: {:?}", addr);
  12.  
  13. let handler = thread::spawn(move || {
  14. // NOTE: You'll need to handle the fact that a single "message"
  15. // may come over the wire in many pieces. Some data formats
  16. // include a length up front that helps, others have specific
  17. // EOF (end of "message") sequences. There are trade-offs.
  18. let mut buf = [0; 10];
  19. socket.read(&mut buf);
  20.  
  21. println!("read: {:?}", buf);
  22. });
  23. handlers.push(handler);
  24. }
  25. Err(e) => println!("couldn't get client: {:?}", e),
  26. }
  27.  
  28. for handler in handlers {
  29. handler.join();
  30. }
  31. }
  32.  
  33. fn client_process() {
  34. let mut stream = TcpStream::connect("127.0.0.1:1337").unwrap();
  35. stream.write(&[1]).unwrap();
  36. }
  37.  
  38. fn main() {
  39. let ps = {
  40. let p1 = thread::spawn(client_process);
  41. let p2 = thread::spawn(network_process);
  42. vec![p1,p2]
  43. // [p1,p2]
  44. };
  45.  
  46. // Wait kindly for all parties to finish.
  47. for process in ps {
  48. process.join();
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement