I am using TcpListener from the standard library
I have a public function that is supposed to start up a listening socket
pub fn start_listen(){
let mut file = File::open("Listen.toml").unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
let value = contents.parse::<Value>().unwrap();
let ip = value["ip"].as_str().unwrap().to_string();
let port = value["port"].as_str().unwrap().to_string();
let socket_string = format!("{}:{}", &ip, &port);
println!("socket_string -> {}", &socket_string);
TcpListener::bind(&socket_string).unwrap();
println!("now listening!");
}
and I call it from main.rs
start_listen::start_listen();
println!("waiting 30s...");
sleep(Duration::from_secs(30));
println!("closing program!");
The problem is the function runs for the 30 seconds and breaks without any errors, but I cannot see the listening socket when I look for it. I am on Ubuntu.
I have tried manually typing in ip and ports like "127.0.0.1:8080" but the program runs just fine without me being able to find that socket.
Does anyone know what issue I am having? Thanks!
EDIT:
The commands I am using to try and see if the listening socket exists
sudo ss -tulpn | grep LISTEN
sudo netstat -tulpn | grep 8080
I do not see anything that indicates that socket exists
EDIT2:
Adding this did nothing
for stream in listener.incoming() {
let stream = stream.unwrap();
println!("Connection established!");
}
The TcpListener::bind
creates a new TcpListener
and returns it. The socket is closed when this TcpListener
is dropped.
Modify your start_listen()
function like this to save the TcpListener
and return it:
pub fn start_listen() -> TcpListener {
...
let listener = TcpListener::bind(&socket_string).unwrap();
println!("now listening!");
listener
}
Then in the main.rs
save the listener before you wait for 30 seconds:
let listener = start_listen::start_listen();
println!("waiting 30s...");
sleep(Duration::from_secs(30));
println!("closing program!");