Created
August 9, 2020 20:47
-
-
Save Heasummn/18acab9769d1bd1c71b1d3b3af2f61f9 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
mod codec; | |
use crate::codec::MQTTCodec; | |
use std::error::Error; | |
use std::net::{IpAddr, Ipv4Addr, SocketAddr}; | |
use tokio::net::{TcpListener, TcpStream}; | |
use tokio_util::codec::{Framed}; | |
use futures::{SinkExt, StreamExt}; | |
use mqttrs::*; | |
#[tokio::main] | |
async fn main() -> Result<(), Box<dyn Error>> { | |
let address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1883); | |
let mut listener = TcpListener::bind(address).await?; | |
loop { | |
let (stream, _addr) = listener.accept().await.unwrap(); | |
println!("New connection: {}", stream.peer_addr().unwrap()); | |
tokio::spawn(async move { | |
handle_client(stream).await; | |
}); | |
} | |
} | |
async fn handle_client(stream: TcpStream) { | |
let mut framed = Framed::new(stream, MQTTCodec::new()); | |
let connect = match framed.next().await { | |
Some(Ok(Packet::Connect(packet))) => { | |
framed.send( | |
Packet::Connack( Connack{ | |
session_present: false, | |
code: ConnectReturnCode::Accepted, | |
}) | |
).await; | |
packet | |
}, | |
_ => { | |
println!("Did not receive connect packet"); | |
return; | |
} | |
}; | |
println!("{:#?}", connect); | |
loop { | |
match framed.next().await { | |
Some(Ok(Packet::Pingreq)) => { | |
framed.send(Packet::Pingresp).await; | |
println!("Ping - Pong!") | |
}, | |
_ => { | |
println!("Received an unknown packet"); | |
break; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment