How to convert "select.select" in python to Rust

Hi.I'm translating a project in python to rust.I had a problem here.
The python goes

self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
readable, _, _ = select.select([self.socket], [], [], 0.0)

I'm not very good at socket.could anyone tells me how to implement this in Rust?
here is some of my after-translate code

use socket::*;
use std::net::{SocketAddr, IpAddr};
use std::str::FromStr;

struct Connection {
    socket : Socket,
    last_sent: String
}
impl Connection
{
    pub fn new(self) -> Connection {
        Connection {
            socket : Socket::new(AF_INET, SOCK_STREAM, 0).expect("Failed to init socket"),
            last_sent: String::new()
        }
    }
    pub fn init(self,address : &str,port : u16)
    {
        self.socket.connect(&SocketAddr::new(IpAddr::from_str(address).expect("Failed to dispatch address"),port)).expect("Failed to connect");
    }
    pub fn drain(self)
    {
        loop {
        }
    }
}
[dependencies]
socket = "0.0.7"
tokio = { version = "1.12.0", features = ["full"] }

Rust has a TcpStream in the standard library, which should work fine here since you're only selecting on one socket (?).

1 Like

Sorry,but what does that mean?

You can open a new TCP connection to a remote server like this:

let stream = TcpStream::connect("www.rust-lang.org:80").expect("couldn't create TCP connection");

This is the equivalent of doing socket.socket(socket.AF_INET, socket.SOCK_STREAM) in Python and then socket.connecting the resulting socket. There are more examples in the TcpStream documentation.

I'm not sure why you're calling select on a single socket; if you just want to check whether a TcpStream is ready for reading, you can do TcpStream::set_nonblocking and then check for read returning an error of kind std::io::ErrorKind::WouldBlock.

In general if you want to be using Tokio, then you should be using the tokio::net::TcpStream type for your sockets.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.