Created
September 22, 2024 10:53
-
-
Save DimitrisCharisis/b76e787c6dd03e6bde7dff54c11d08f9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| #![allow(unused_imports)] | |
| use std::net::TcpListener; | |
| use std::io::prelude::*; | |
| struct Response <'a> { | |
| length: i32, | |
| header: &'a [u8], | |
| body: &'a [u8], | |
| } | |
| impl <'a> Response<'a>{ | |
| fn new(length: i32, header: &'a [u8], body: &'a [u8]) -> Self { | |
| Response { | |
| length, | |
| header, | |
| body, | |
| } | |
| } | |
| fn to_raw_bytes(&self) -> Vec<u8> { | |
| let mut ret = vec![]; | |
| ret.extend(self.length.to_be_bytes()); | |
| for i in self.header { | |
| ret.push(*i); | |
| } | |
| for i in self.body { | |
| ret.push(*i) | |
| } | |
| ret | |
| } | |
| } | |
| fn main() { | |
| // You can use print statements as follows for debugging, they'll be visible when running tests. | |
| println!("Logs from your program will appear here!"); | |
| // Uncomment this block to pass the first stage | |
| let listener = TcpListener::bind("127.0.0.1:9092").unwrap(); | |
| let mut req = [0; 12]; | |
| for stream in listener.incoming() { | |
| match stream { | |
| Ok(mut _stream) => { | |
| println!("accepted new connection"); | |
| _stream.read(&mut req) | |
| .expect("Read from TcpStream Failed"); | |
| println!("req = {:?}", req); | |
| let v = Response::new(8, &req[8..12], &[]) | |
| .to_raw_bytes(); | |
| println!("v = {:?}", v); | |
| let num = u32::from_be_bytes([v[4], v[5], v[6], v[7]]); | |
| println!("NUM = {num}"); | |
| _stream.write(&v) | |
| .expect("Write to TcpStream Failed"); | |
| } | |
| Err(e) => { | |
| println!("error: {}", e); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment