【问题标题】:Why is the client not connecting to my tcp server?为什么客户端没有连接到我的 tcp 服务器?
【发布时间】:2022-01-15 23:25:40
【问题描述】:

尽管如此,我还是无法使用客户端连接到我的服务器。我的笔记本电脑充当客户端,我的 PC 充当服务器,它们连接到同一个 wifi。我尝试关闭 Windows 防火墙,但没有帮助。这是我的笔记本电脑(客户端)收到的错误代码:Error: Os { code: 10061, kind: ConnectionRefused, message: "No connection could be made because the target machine actively refused it." }

在笔记本电脑上运行的客户端代码:

use std::io::prelude::*;
use std::net::TcpStream;

fn main() -> std::io::Result<()> {
    let mut stream = TcpStream::connect("localhost:8080")?;

    stream.write(&[1])?;
    stream.read(&mut [0; 128])?;
    Ok(())
} // the stream is closed here

在 PC 上运行的服务器代码:

use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::io::{BufReader,BufWriter};

fn handle_client(stream: TcpStream) {
    // ...
    let mut reader = BufReader::new(&stream);
    let mut response = String::new();
    reader.read_to_string(&mut response).unwrap();
    println!("{}", response);
}

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("0.0.0.0:8080")?;

    // accept connections and process them serially
    for stream in listener.incoming() {
        handle_client(stream?);
    }
    Ok(())
}

【问题讨论】:

  • 我很确定 localhost 不是您其他机器的地址,因此名称为 LOCAL 主机。
  • 是这个问题吗? @Stargateur
  • 你是机器A,你尝试联系机器B,但是使用机器A的locahost,你需要机器B的ip
  • 好的,请问如何获取服务器的ip? @Stargateur
  • 我是否可以建议您在直接进入自定义 Rust 代码之前,确保您可以使用更简单、久经考验的工具(如 nc (netcat))创建 TCP 连接?这样你就会知道问题出在你的代码中,而不是连接本身(我怀疑这里就是这种情况)。

标签: windows rust server tcp port


【解决方案1】:

您需要指定另一台机器的主机名或 IP,而不是 localhost。您可以手动找到它并对其进行硬编码。如果您希望您的程序自动找到本地网络上的另一台机器,那就是a complex annoying problem,它本身比您在这里尝试做的要大得多。

连接两台机器后,你会发现你的程序卡住了。

这是因为read_to_string 在连接完全关闭之前不会停止读取。 TCP不是基于消息的,所以对方不会读到一个write,会一直读,一直等到对方挂断。您需要设计一个协议,在读取它们之前确切知道需要读取多少字节,并且不会要求更多字节(例如,在字符串之前发送字符串的长度)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 2017-07-15
    • 2022-01-16
    • 2019-06-06
    • 2019-06-18
    相关资源
    最近更新 更多