Skip to content

Instantly share code, notes, and snippets.

@Leonti
Created October 19, 2018 02:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Leonti/874815f6c63ac336a1be08000cbe7175 to your computer and use it in GitHub Desktop.
Save Leonti/874815f6c63ac336a1be08000cbe7175 to your computer and use it in GitHub Desktop.
Use of moved value
#![allow(unused)]
#[macro_use]
extern crate crossbeam_channel;
use crossbeam_channel as channel;
use std::io::Write;
use std::io;
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::time;
use std::sync::{Arc,RwLock};
// https://github.com/Nervengift/chat-server-example/blob/master/src/main.rs
fn handle_client(mut stream: TcpStream, recv: channel::Receiver<String>) {
println!("Client connected");
loop {
{
let msg = recv.recv().unwrap();
println!("DEBUG arc.read() => {:?}", msg);
stream.write_fmt(format_args!("{}", msg)).unwrap();
}
}
}
struct Connection {
sender: channel::Sender<String>,
id: usize
}
fn main() -> io::Result<()> {
let mut connections: Vec<Connection> = Vec::new();
thread::spawn(move|| {
loop {
for i in 1..1000 {
for connection in connections.iter() {
println!("DEBUG messages in the channel {:?}", connection.sender.len());
connection.sender.send(format!("Test message {}", i));
}
thread::sleep(time::Duration::from_millis(500));
}
}
});
let listener = TcpListener::bind("0.0.0.0:9999")?;
let mut client_count = 0;
for stream in listener.incoming() {
client_count += 0;
let (s, r) = channel::unbounded();
let connection = Connection {
sender: s,
id: client_count
};
connections.push(connection); // use of moved value `connections`
thread::spawn(|| {
handle_client(stream.unwrap(), r);
});
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment