Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::io::prelude::*;
- use std::thread;
- use std::net::{TcpStream, TcpListener};
- fn network_process() {
- let listener = TcpListener::bind("127.0.0.1:1337").unwrap();
- let mut handlers = Vec::new();
- match listener.accept() {
- Ok((mut socket, addr)) => {
- println!("new client: {:?}", addr);
- let handler = thread::spawn(move || {
- // NOTE: You'll need to handle the fact that a single "message"
- // may come over the wire in many pieces. Some data formats
- // include a length up front that helps, others have specific
- // EOF (end of "message") sequences. There are trade-offs.
- let mut buf = [0; 10];
- socket.read(&mut buf);
- println!("read: {:?}", buf);
- });
- handlers.push(handler);
- }
- Err(e) => println!("couldn't get client: {:?}", e),
- }
- for handler in handlers {
- handler.join();
- }
- }
- fn client_process() {
- let mut stream = TcpStream::connect("127.0.0.1:1337").unwrap();
- stream.write(&[1]).unwrap();
- }
- fn main() {
- let ps = {
- let p1 = thread::spawn(client_process);
- let p2 = thread::spawn(network_process);
- vec![p1,p2]
- // [p1,p2]
- };
- // Wait kindly for all parties to finish.
- for process in ps {
- process.join();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement