homework: reduce panics
This commit is contained in:
@@ -1,10 +1,11 @@
|
||||
use smart_house::PowerSocket;
|
||||
use std::time::Duration;
|
||||
|
||||
fn main() {
|
||||
let mut power_socket = PowerSocket::connect("127.0.0.1:10001");
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut power_socket = PowerSocket::connect("127.0.0.1:10001")?;
|
||||
println!("{}", power_socket.display());
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
power_socket.set_on(!power_socket.is_on());
|
||||
println!("{}", power_socket.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::cell::RefCell;
|
||||
use std::fmt::{Debug, Display};
|
||||
use std::io;
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::time::Duration;
|
||||
@@ -16,10 +17,9 @@ impl PowerSocket {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn connect(addr: &str) -> Self {
|
||||
Self {
|
||||
handle: Box::new(PowerSocketClient::new(addr)),
|
||||
}
|
||||
pub fn connect(addr: &str) -> Result<Self, io::Error> {
|
||||
let handle = PowerSocketClient::new(addr)?;
|
||||
Ok(Self { handle: Box::new(handle) })
|
||||
}
|
||||
|
||||
pub fn is_on(&self) -> bool {
|
||||
@@ -82,12 +82,12 @@ struct PowerSocketClient {
|
||||
}
|
||||
|
||||
impl PowerSocketClient {
|
||||
pub fn new(addr: &str) -> Self {
|
||||
let addr: SocketAddr = addr.parse().expect("addr should be valid tcp address");
|
||||
let stream = TcpStream::connect_timeout(&addr, TIMEOUT).expect("address should be available to connect");
|
||||
stream.set_write_timeout(Some(TIMEOUT)).expect("write timeout should be set");
|
||||
stream.set_read_timeout(Some(TIMEOUT)).expect("read timeout should be set");
|
||||
Self { stream: RefCell::new(stream) }
|
||||
fn new(addr: &str) -> Result<Self, io::Error> {
|
||||
let addr: SocketAddr = addr.parse().map_err(io::Error::other)?;
|
||||
let stream = TcpStream::connect_timeout(&addr, TIMEOUT)?;
|
||||
stream.set_write_timeout(Some(TIMEOUT))?;
|
||||
stream.set_read_timeout(Some(TIMEOUT))?;
|
||||
Ok(Self { stream: RefCell::new(stream) })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user