Created
August 25, 2015 19:01
-
-
Save gkbrk/bea6dee7c0478395b718 to your computer and use it in GitHub Desktop.
Dictionary server in Rust.
This file contains 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::prelude::*; | |
use std::net::{TcpListener, TcpStream}; | |
use std::io::BufReader; | |
use std::thread; | |
use std::fs::File; | |
fn get_definitions(word: String) -> Vec<String>{ | |
let mut dict = File::open("dict.txt").unwrap(); | |
let mut reader = BufReader::new(dict); | |
let mut matches: Vec<String> = Vec::new(); | |
for line in reader.lines(){ | |
let line = line.unwrap(); | |
let parts: Vec<&str> = line.trim().splitn(2, ": ").collect(); | |
let dictword = parts[0]; | |
let definition = parts[1]; | |
if dictword.to_lowercase() == word.to_lowercase(){ | |
matches.push(definition.to_string()); | |
} | |
} | |
return matches; | |
} | |
fn handle_client(mut stream: TcpStream) { | |
let mut reader = BufReader::new(stream.try_clone().unwrap()); | |
stream.write("220 rustdict 0.1.0\r\n".as_bytes()); | |
loop { | |
let mut line = String::new(); | |
let line_len = reader.read_line(&mut line).unwrap(); | |
if line_len > 0{ | |
let pieces: Vec<&str> = line.trim().split(" ").collect(); | |
match pieces[0] { | |
"define" => { | |
let word = pieces[2].replace("\"", ""); | |
let definitions = get_definitions(word.clone()); | |
stream.write("250 ok\r\n".as_bytes()); | |
stream.write(format!("150 {} definitions received\r\n", definitions.len()).as_bytes()); | |
for definition in definitions.iter(){ | |
stream.write(format!("151 \"{}\" \"default dictionary\"\r\n{}\r\n.\r\n", word, definition).as_bytes()); | |
} | |
stream.write("250 ok\r\n".as_bytes()); | |
}, | |
"quit" => { | |
stream.write("221 bye\r\n".as_bytes()); | |
break; | |
}, | |
_ => { | |
println!("{}", line.trim()); | |
} | |
} | |
}else{ | |
println!("Client disconnected"); | |
break; | |
} | |
} | |
} | |
fn main() { | |
let listener = TcpListener::bind("0.0.0.0:2628").unwrap(); | |
for stream in listener.incoming() { | |
match stream { | |
Ok(stream) => { | |
thread::spawn(move|| { | |
handle_client(stream); | |
}); | |
}, | |
Err(e) => { | |
println!("Connection failed."); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment