2016-10-31 137 views
0

我已經在Rust中編寫了一個基本的TCP服務器,但我無法從同一網絡上的其他計算機訪問它。這不是網絡問題,因爲我也編寫了一個類似的Python TCP服務器,並且測試客戶端能夠成功連接到該服務器。無法從外部機器連接到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(); 
} 

回答

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

如果您綁定到127.0.0.1:xxxx,插座只能從本地主機接口聽。要允許外部連接,請改爲綁定到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"); 
+2

我不知道主機OP的「類似Python的TCP服務器」監聽... – Shepmaster

+0

感謝@kennytm,我想通了,你回答之前並沒有得到更新我的問題的時候這個問題。正如你所提到的那樣,將我的IP設置爲0.0.0.0,現在我的服務器正在工作。再次感謝您的回答。 – varagrawal

+0

'Result :: expect'會使報告的行出現錯誤。因此,如果讓Err(err)= ... {恐慌! (「message,{}」,err)}'通常在錯誤實際發生時更有幫助。 – ArtemGr

相關問題