tcp / udp 服务器-客户端中的 Udp 套接字

问题描述 投票:0回答:0

在这里通过 tcp 和 udp 构建客户端-服务器架构。

我已经很好地启动并运行了 tcp,每个连接的客户端都有一个 TcpStream,用于从/向该客户端读取/发送数据。

现在,我在保持一致的 udp 连接时遇到了麻烦:我对 UdpSocket 很困惑,并且真的不明白如何设置和运行它们。

对于一些上下文,我有这些结构来保持我的客户端连接在服务器端:

/// Server representation of a Client
pub struct Connection {
    id: usize,
    tcp_connection: TcpStream,
    incoming_packet: Option<Packet>,
    buffer: NetworkBuffer,
}

这是我的服务器结构,有一个 TcpListener 来监听传入的连接:

/// Server system. When created, will start to listen tcp connections and create Connection when receiving them.
pub struct Server {
    connections: HashMap<usize, Connection>,
    max_client_count: usize,
    current_client_count: usize,
    next_available_id: usize,
    tcp_listener: TcpListener,
}

我的服务器监听传入的 tcp 连接,并相应地创建客户端:

match self.tcp_listener.accept() {
    Ok((stream, adress)) => self.handle_incoming_connection(stream, adress),
    Err(_e) => {/* Error handling */},
}

在客户端,我只有一个

TcpStream
尝试连接到服务器,然后准备好向服务器发送消息/从服务器读取消息。

/// client representation of the connection to the server
pub struct Client {
    server_addr: SocketAddr,
    tcp_connection: Option<TcpStream>,
    tcp_buffer: NetworkBuffer,
    tcp_incoming_packet: Option<Packet>,
    tcp_connecting_thread: Option<JoinHandle<Result<TcpStream, String>>>,
}

我对tcp不是很熟悉,对udp就更不熟悉了。我不认为有“Udp 连接”之类的东西? 那么如何在客户端/服务器架构中以两端可以相互发送数据的方式实现 udp 呢?我应该有什么结构?

rust udp
© www.soinside.com 2019 - 2024. All rights reserved.