Rustで基本的なTCPサーバーを作成しましたが、同じネットワーク上の別のコンピューターからアクセスできません。同様のPythonTCPサーバーも作成し、テストクライアントはそのサーバーに正常に接続できるため、ネットワークの問題ではありません。
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();
}
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();
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(_) => (),
}
"aaa".as_bytes()
あなたの代わりに単に書くことができますb"aaa"
。
// better
stream.write(b"This works!").expect("Read-Server: Error writing to stream");
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加