Skip to content

Instantly share code, notes, and snippets.

@ZaWertun
Forked from andelf/simple_chat.rs
Last active August 29, 2015 14:00
Show Gist options
  • Save ZaWertun/11398196 to your computer and use it in GitHub Desktop.
Save ZaWertun/11398196 to your computer and use it in GitHub Desktop.
compatible with rust 0.10
#![allow(unused_must_use)]
extern crate sync;
// str op trait
use std::str::StrSlice;
// for tcp listen
use std::io::{TcpListener, TcpStream};
use std::io::net::ip::SocketAddr;
// for trait
use std::io::{Listener, Writer, Acceptor, Buffer};
// for spawn
use std::task::spawn;
// for read_line
use std::io::BufferedStream;
// for gathering chat msg
use std::comm::channel;
// for chat msg storage
use sync::{RWLock, Arc};
fn chat_loop(ss: &mut BufferedStream<TcpStream>, chan: Sender<~str>, arc: Arc<RWLock<~[~str]>>) {
ss.write(bytes!("Welcome to Simple Chat Server!\n"));
ss.write(bytes!("Plz input yourname: "));
ss.flush();
let mut name : ~str = ss.read_line().unwrap();
name = name.trim_right().into_owned();
ss.write_str(format!("Hello, {}!\n", name));
ss.flush();
let mut pos = 0;
loop {
{
let val = arc.read();
println!("DEBUG arc.read() => {}", (*val).to_str())
for i in range(pos, (*val).len()) {
ss.write_str((*val)[i]);
}
pos = (*val).len();
}
ss.write(bytes!(" > "));
ss.flush();
let reads = ss.read_line().unwrap();
if reads.trim().len() != 0 {
println!("DEBUG reads len =>>>>> {}", reads.len());
chan.send(format!("[{}] said: {}", name, reads));
println!("DEBUG: got '{}' from {}", reads.trim(), name);
}
}
}
fn main () {
let addr : SocketAddr = from_str("127.0.0.1:8888").unwrap();
let listener = TcpListener::bind(addr).unwrap();
let mut acceptor = listener.listen().unwrap();
let (chan, port) = channel();
let arc : Arc<RWLock<~[~str]>> = Arc::new(RWLock::new(~[]));
let arc_w = arc.clone();
spawn(proc() {
loop {
let msg: ~str = port.recv();
print!("DEBUG: {}", msg);
let mut val = arc_w.write();
(*val).push(msg.to_str());
}
});
loop {
match acceptor.accept() {
Err(_) => println!("error listen"),
Ok(mut stream) => {
println!("DEBUG: got connection from {} to {}",
stream.peer_name().unwrap().to_str(),
stream.socket_name().unwrap().to_str());
let chan = chan.clone();
let arc = arc.clone();
spawn(proc() {
let mut stream = BufferedStream::new(stream);
chat_loop(&mut stream, chan, arc);
});
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment