Created
July 9, 2014 21:05
-
-
Save soarez/d58ec4a387c8e98395c8 to your computer and use it in GitHub Desktop.
a non working tcp chat server in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io::{Listener, Acceptor}; | |
use std::io::net::ip::{Ipv4Addr, SocketAddr}; | |
use std::io::net::tcp::{TcpListener, TcpStream}; | |
use std::io::BufferedStream; | |
struct Client { | |
id: u16, | |
stream: BufferedStream<TcpStream> | |
} | |
struct Msg { | |
from: u16, | |
text: String | |
} | |
fn main() { | |
let mut acceptor = TcpListener::bind("127.0.0.1", 1337).listen().unwrap(); | |
let (chan, port): (Sender<Msg>, Receiver<Msg>) = channel(); | |
let mut connected: Vec<Client> = Vec::new(); | |
spawn(proc() { | |
loop { | |
let msg = port.recv(); | |
for client in connected.iter() { | |
if msg.from != client.id { | |
client.stream.write_line(msg.text.as_slice()).unwrap(); | |
client.stream.flush().unwrap(); | |
} | |
} | |
} | |
}); | |
for opt_stream in acceptor.incoming() { | |
spawn(proc() { | |
let tcp_stream = opt_stream.unwrap(); | |
let mut stream = BufferedStream::new(tcp_stream); | |
let id = tcp_stream.peer_name().unwrap().port; | |
connected.push(Client{id: id, stream: BufferedStream::new(tcp_stream)}); | |
let my_chan = chan.clone(); | |
loop { | |
match stream.read_line() { | |
Ok(line) => { my_chan.send(Msg{text: line, from: id}); }, | |
_ => break | |
}; | |
}; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment