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();
}
我不知道主機OP的「類似Python的TCP服務器」監聽... – Shepmaster
感謝@kennytm,我想通了,你回答之前並沒有得到更新我的問題的時候這個問題。正如你所提到的那樣,將我的IP設置爲0.0.0.0,現在我的服務器正在工作。再次感謝您的回答。 – varagrawal
'Result :: expect'會使報告的行出現錯誤。因此,如果讓Err(err)= ... {恐慌! (「message,{}」,err)}'通常在錯誤實際發生時更有幫助。 – ArtemGr