Skip to content

Instantly share code, notes, and snippets.

@Heasummn
Created Aug 9, 2020
Embed
What would you like to do?
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