【发布时间】: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();
}
【问题讨论】: