I have a class called connection in java.
//the constructor and the function I need to implement
Connection(String host, int port) {
Log.info("Connecting to " + host + ":" + port);
if (host != null) {
try {
this.socket = new Socket(host, port);
socket.setTcpNoDelay(true);
socket.setKeepAlive(true);
socket.setTrafficClass(0x10);
this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
} catch (IOException e) {
throw new ConnectionException("Couldn't connect to Minecraft, is it running?");
}
}
Log.info("Connected");
}
static class ConnectionException extends RuntimeException {
ConnectionException(String message) {
super(message);
}
ConnectionException(Throwable cause) {
super(cause);
}
//function
String receive() {
try {
return in.readLine();
} catch (IOException e) {
throw new ConnectionException(e);
}
}
I implement it in rust
//still constructor and function
pub fn new<A : ToSocketAddrs>(address : A) -> Connection {
Connection {
socket : TcpStream::connect(address).expect("Couldn't connect to Minecraft, is it running?"),
auto_flush: true
}
}
pub fn receive(self) -> String {
self.clone().socket.set_nonblocking(false).expect("Failed to set non-blocking");
self.clone().socket.set_read_timeout(Some(Duration::from_secs(1))).expect("Failed to set read timeout");
let mut s = String::new();
self.clone().socket.read_to_string(&mut s).expect("Failed to read from socket");
self.clone().socket.set_nonblocking(true).expect("Failed to set non-blocking");
s.replace("\n","").to_string()
}
I do some test and found that the Rust version is always timeout but java runs successfully.
What's the problem in my function?