无法从外部计算机连接到TCP服务器

时间:2016-10-31 15:19:32

标签: sockets tcp rust

我在Rust中编写了一个基本的TCP服务器,但我无法从同一网络上的其他计算机访问它。这不是网络问题,因为我也编写了类似的Python TCP服务器,测试客户端能够成功连接到该服务器。

use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::str;

fn handle_read(mut stream: TcpStream) {
    let mut buf;
    // clear out the buffer so we don't send garbage
    buf = [0; 512];

    // Read and discard any data from the client since this is a read only server.
    let _ = match stream.read(&mut buf) {
        Err(e) => panic!("Got an error: {}", e),
        Ok(m) => m,
    };

    println!("Got some data");

    // Write back the response to the TCP stream
    match stream.write("This works!".as_bytes()) {
        Err(e) => panic!("Read-Server: Error writing to stream {}", e),
        Ok(_) => (),
    }

}

pub fn read_server() {
    // Create TCP server
    let listener = TcpListener::bind("127.0.0.1:6009").unwrap();
    println!("Read server listening on port 6009 started, ready to accept");

    // Wait for incoming connections and respond accordingly
    for stream in listener.incoming() {
        match stream {
            Err(_) => {
                println!("Got an error");
            }
            Ok(stream) => {

                println!("Received a connection");
                // Spawn a new thread to respond to the connection request
                thread::spawn(move || {
                    handle_read(stream);

                });

            }    
        }

    }
}

fn main() {
    read_server();
}

1 个答案:

答案 0 :(得分:4)

let listener = TcpListener::bind("127.0.0.1:6009").unwrap();

如果绑定到127.0.0.1:xxxx,套接字只能从localhost接口侦听。要允许外部连接,请绑定到0.0.0.0,以便它可以接受来自所有网络接口的连接。

let listener = TcpListener::bind("0.0.0.0:6009").unwrap();

有关详细信息,请参阅Why would I bind on a different server than 127.0.0.1?

BTW,(1)

// not idiomatic
let _ = match stream.read(&mut buf) {
    Err(e) => panic!("Got an error: {}", e),
    Ok(m) => m,
};

您可以使用Result::expect

// better
stream.read(&mut buf).expect("Got an error");

(2)

// not idiomatic
match stream.write("This works!".as_bytes()) {
    Err(e) => panic!("Read-Server: Error writing to stream {}", e),
    Ok(_) => (),
}

而不是"aaa".as_bytes(),您只需撰写b"aaa"

// better
stream.write(b"This works!").expect("Read-Server: Error writing to stream");