Search code examples
rusttcplistener

Getting "Invalid port value" with TcpListener


I'm trying to get my program to run a websocket server using tungstenite and TcpListener, but unfortunately, it throws an invalid port error.

thread 'main' panicked at 'Invalid address format: Error { kind: InvalidInput, message: "invalid port value"
fn run_server(port: String) {
    let form_port = String::from(format!("{}:{}", String::from("127.0.0.1"),port));
    println!("Full Host: {}", form_port);
    let server = TcpListener::bind(form_port).unwrap(); //The error
    for stream in server.incoming() {
        spawn (move || {
            let mut websocket = accept(stream.unwrap()).unwrap();
            loop {
                let msg = websocket.read().unwrap();

                if msg.is_binary() || msg.is_text() {
                    websocket.send(msg).unwrap();
                }
            }
        });
    }
}

That's the part gives the error. But if I set the host manually, it works:

fn run_server(/* port: String */) {
    let form_port = String::from("127.0.0.1:1"); //Trying manually
    println!("Full Host: {}", form_port);
    let server = TcpListener::bind(form_port).unwrap();
    for stream in server.incoming() {
        spawn (move || {
            let mut websocket = accept(stream.unwrap()).unwrap();
            loop {
                let msg = websocket.read().unwrap();

                if msg.is_binary() || msg.is_text() {
                    websocket.send(msg).unwrap();
                }
            }
        });
    }
}

Solution

  • It gave the error because the port has a \n by default. I just trimmed it.