Skip to content

Instantly share code, notes, and snippets.

@antonva
Created May 22, 2014 00:07
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 antonva/7c0602d47f42685f2619 to your computer and use it in GitHub Desktop.
Save antonva/7c0602d47f42685f2619 to your computer and use it in GitHub Desktop.
extern crate sync; /* For the duplex*/
use std::os;
use std::path::BytesContainer;
use std::vec::Vec;
use std::io::net::tcp::TcpStream;
fn handle_connection( stream: TcpStream )
{
let ( from_stream, to_irc ) = sync::duplex();
let ( from_irc, to_stream ) = sync::duplex();
let tcp_recv = stream.clone();
let tcp_write = stream.clone();
/*
* TODO: create TaskBuilder objects for these tasks, named tasks should be
*proper form.
*/
spawn( proc() { handle_read( tcp_recv, &from_stream ) });
spawn( proc() { irc_handler( &to_irc, &from_irc ) });
spawn( proc() { handle_write( tcp_write, &to_stream ) });
}
fn handle_read(mut stream: TcpStream,
channel: &sync::DuplexStream<StrBuf, StrBuf> )
{
let mut tcp_buf : Vec<u8> = Vec::new();
let mut buf = [0];
loop {
match stream.read(buf) {
Ok(_) => {
match buf[0] {
/* Eat the \r. */
13 => { }
/* Send received messages on \n */
10 => {
channel.send(
tcp_buf.container_as_str().unwrap().to_strbuf()
);
/* Clear tcp_buf after sending message.*/
tcp_buf.truncate(0);
}
/* Push the rest of the bytes into buffer.*/
_ => {
tcp_buf.push(buf[0]);
}
}
},
Err(err) => {
println!("Error: {}", err);
break;
}
};
};
}
fn handle_write( mut stream: TcpStream,
channel: &sync::DuplexStream<StrBuf, StrBuf> )
{
//let mut _r = stream.write("NICK RustBOT\r\n".as_bytes());
//_r = stream.write("USER rusty 0 * :Rusty McRust\r\n".as_bytes());
loop {
let mut write_string = channel.recv();
println!("{}", write_string);
write_string.push_char('\r');
write_string.push_char('\n');
let _ = stream.write(write_string.as_bytes());
}
}
fn irc_handler( from_server: &sync::DuplexStream<StrBuf, StrBuf>,
to_server : &sync::DuplexStream<StrBuf, StrBuf> )
{
loop {
let server_string = from_server.recv();
//let s : &str = server_string.to_str();
//if s.slice(0,12) == "NOTICE AUTH" {
to_server.send(StrBuf::from_str("NICK rust-bot-test"));
to_server.send(StrBuf::from_str("USER rust-bot-test 0 * :rust-bot-test"));
//}
to_server.send(server_string);
}
}
/* Main function */
fn main() {
let args = os::args();
println!("Argument test: {}", args);
//let stream = TcpStream::connect("77.80.253.131", 6667);
let stream = TcpStream::connect("88.198.243.211", 6667);
//let stream = TcpStream::connect("127.0.0.1", 9123);
match stream {
Err(e) => { println!("Error: {}", e) }
Ok(stream) => { handle_connection(stream); }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment