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