Put the structures 'Server' and 'Client' in the same module called 'end_point'.
[crypto_lab1.git] / src / server.rs
index 3eb1a46..b655ae7 100644 (file)
@@ -1,19 +1,17 @@
-use std::io::{ TcpListener, TcpStream, Acceptor, Listener, IoError, IoResult };
+use std::io::{ TcpListener, TcpStream, Acceptor, Listener, IoError, IoResult, EndOfFile };
 use std::io::net::tcp::{ TcpAcceptor };
-use command::{ Command, Packet, Error };
-use crypto::Crypto;
+use packet::{ Packet, IOReadError };
 
 pub struct Server {
-   acceptor: TcpAcceptor,
-   crypto: Crypto
+   acceptor: TcpAcceptor
 }
 
 impl Server {
    pub fn new(port: u16) -> IoResult<Server> {
       let mut acceptor = try!(TcpListener::bind("127.0.0.1", port).listen());
+      
       let server = Server { 
-         acceptor: acceptor.clone(),  
-         crypto: Crypto::new()
+         acceptor: acceptor.clone()
       };
       
       spawn(proc() {
@@ -36,13 +34,28 @@ impl Server {
       self.acceptor.close_accept()
    }
    
-   fn handle_client(mut stream: TcpStream) {   
-      println!("new connection!");
+   fn handle_client(mut stream: TcpStream) { 
       let mut current_timestamp = 0u64;
-      match Packet::read(&mut stream) {
-         Ok(Command(packet)) => println!("CommandPacket"),
-         Ok(Error(packet)) => println!("AnswerPacket"),
-         Err(io_error) => println!("IO Error")
+      
+      loop {
+         // stream.set_timeout(Some(1000000000));         
+         match Packet::read(&mut stream) {
+            Ok(packet) => {
+               if packet.timestamp <= current_timestamp {
+                  println!("Error, timestamp mismatch, current timestamp: {}, packet received: {}", current_timestamp, packet);
+               } else {
+                  current_timestamp += 1;
+                  println!("Receive packet: {}", packet);
+               }
+            },
+            // Socket has been closed.
+            Err(IOReadError(IoError { kind: EndOfFile, .. })) => {
+               return;
+            },
+            Err(e) => {
+               println!("Read error: {}", e)
+            }
+         }
       }
    }
 }
\ No newline at end of file