【问题标题】:Unable to connect to TCP Server from external machine无法从外部机器连接到 TCP Server
【发布时间】:2016-10-31 15:19:31
【问题描述】:

我已经用 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();
}

【问题讨论】:

    标签: sockets tcp rust


    【解决方案1】:
    let listener = TcpListener::bind("127.0.0.1:6009").unwrap();
    

    如果绑定到127.0.0.1:xxxx,则socket只能从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?


    顺便说一句,(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(_) => (),
    }
    

    您可以简单地写成b"aaa",而不是"aaa".as_bytes()

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

    【讨论】:

    • 谢谢@kennytm,我在你回答之前就发现了这个问题,没有时间更新我的问题。就像您提到的那样,将我的 IP 设置为 0.0.0.0 现在我的服务器可以正常工作了。再次感谢您的回答。
    • Result::expect 将破坏报告的行。因此,当错误实际发生时,if let Err (err) = ... {panic! ("message, {}", err)} 通常更有帮助。
    • @ArtemGr 希望有人会推动internals.rust-lang.org/t/… 所以expect 的行号是正确的。但是有了足够独特的消息,应该不难找到我们的哪个expect 出了问题。
    猜你喜欢
    • 2018-01-04
    • 2020-06-12
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    • 2013-05-07
    相关资源
    最近更新 更多