Last active
August 29, 2015 13:59
-
-
Save Noxivs/10561528 to your computer and use it in GitHub Desktop.
simple tcp server
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::net::ip::{Ipv4Addr, SocketAddr}; | |
use std::io::net::tcp::{TcpListener, TcpStream}; | |
use std::io::{Acceptor, Listener, IoResult}; | |
struct Client { | |
stream: TcpStream | |
} | |
impl Client { | |
pub fn new(connec: TcpStream) -> Client { Client { | |
stream: connec | |
} } | |
pub fn begin_receive(&mut self) -> () { | |
self.receive_msg(); | |
} | |
fn receive_msg(&mut self) { | |
let mut buf = [0, ..2047]; | |
let _res = self.stream.read(buf); | |
let data = std::str::from_utf8(buf).unwrap(); | |
let data = std::str::replace(data, "\u0000", ""); | |
let data = std::str::replace(data, "\n", ""); | |
self.handle_msg(data); | |
} | |
fn handle_msg(&mut self, msg: ~str) { | |
println!("{}", msg); | |
self.receive_msg(); | |
} | |
} | |
fn main() { | |
let addr = SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 443}; | |
let listener = TcpListener::bind(addr); | |
let mut acceptor = listener.unwrap().listen(); | |
println!("Server started on {}", addr); | |
for mut stream in acceptor.incoming() { | |
let (tx, rx) = channel(); | |
tx.send(stream.clone()); | |
spawn(proc() { | |
let local_stream = rx.recv(); | |
let mut client = create_client(local_stream); | |
client.begin_receive(); | |
}); | |
let writer = &mut stream; | |
let _result = writer.write(bytes!("HCazertyuiopqsdfghjklmwxcvbnazyert\x0000")); | |
} | |
} | |
fn create_client(result: IoResult<TcpStream>) -> Client { | |
let stream = result.unwrap(); | |
return Client::new(stream); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment