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!");
}
2
Answers
To answer my own question, the socket gets deleted when the start_listen public function gets out of scope. Adding a timer to that function confirmed this, guess I need to figure out how to make sure it doesn't go out of scope
The
TcpListener::bind
creates a newTcpListener
and returns it. The socket is closed when thisTcpListener
is dropped.Modify your
start_listen()
function like this to save theTcpListener
and return it:Then in the
main.rs
save the listener before you wait for 30 seconds: