tcpstream passing a simple demo test

not sure what other tests to run, not an expert in this stuff.
This commit is contained in:
bunnie 2022-01-31 14:35:55 +08:00
parent 2153c25be3
commit 0910f7e373
4 changed files with 50 additions and 12 deletions

View file

@ -435,6 +435,7 @@ fn xmain() -> ! {
shutdown_rx: false,
};
tcp_handles.insert(connection, tcp_cb_state);
tcpspec.local_port = Some(local_port);
tcpspec.result = Some(NetMemResponse::Ok);
}
Err(e) => {
@ -540,19 +541,22 @@ fn xmain() -> ! {
};
if let Some(tcp_state) = tcp_handles.get(&connection) {
let mut socket = sockets.get::<TcpSocket>(tcp_state.handle);
if socket.can_send() {
tcp_tx.result = match socket.send_slice(&tcp_tx.data) {
if socket.may_send() {
tcp_tx.result = match socket.send_slice(&tcp_tx.data[..tcp_tx.len as usize]) {
Ok(octets) => {
log::trace!("sent {}", octets);
tcp_tx.len = octets as u16;
Some(NetMemResponse::Sent(octets as u16))
},
Err(_) => Some(NetMemResponse::LibraryError),
}
} else {
log::trace!("tx can't send, please retry");
// inform the sender it should retry
tcp_tx.result = Some(NetMemResponse::SocketInUse);
}
} else {
log::trace!("tx spec invalid");
tcp_tx.result = Some(NetMemResponse::Invalid);
}
buf.replace(tcp_tx).unwrap();

View file

@ -96,6 +96,7 @@ impl TcpStream {
Some(NetTcpCallback::RxData) => {
let buffer = unsafe {Buffer::from_memory_message(msg.body.memory_message().unwrap())};
let incoming = buffer.as_flat::<NetTcpResponse, _>().unwrap();
log::trace!("rx data({})", incoming.len);
{ // grab the lock once for better efficiency
let mut rx_locked = rx_buf.lock().unwrap();
for &d in incoming.data[..incoming.len as usize].iter() {
@ -334,6 +335,7 @@ impl fmt::Debug for TcpStream {
impl Read for TcpStream {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if self.nonblocking {
log::trace!("nonblocking");
if self.rx_buf.lock().unwrap().len() == 0 {
return Err(Error::new(ErrorKind::WouldBlock, "Read would block"));
} else {
@ -345,24 +347,28 @@ impl Read for TcpStream {
return Ok(readlen)
}
} else {
log::trace!("blocking");
let start = self.ticktimer.elapsed_ms();
while self.ticktimer.elapsed_ms() - start <
self.read_timeout.unwrap_or(Duration::from_millis(u64::MAX)).millis() {
self.read_timeout.unwrap_or(Duration::from_millis(u64::MAX)).total_millis() {
if self.rx_buf.lock().unwrap().len() == 0 {
// this limits our poll interval frequency. We do this mainly to save power --
// we certainly could do a xous::yield_slice(); which would cause this to immediately
// and furiously return if the system is busy-waiting, but this will also increase
// battery usage by quite a bit.
log::trace!("wait rx retry");
self.ticktimer.sleep_ms(RX_POLL_INTERVAL_MS).unwrap();
} else {
let mut rx_buf = self.rx_buf.lock().unwrap();
let readlen = rx_buf.len().min(buf.len());
log::trace!("got {} bytes", readlen);
for (src, dst) in rx_buf.drain(..readlen).zip(buf.iter_mut()) {
*dst = src;
}
return Ok(readlen)
}
}
log::trace!("timed out");
// the return code in this case varies by platform. We're going with what the docs say is the "Unix" way.
return Err(Error::new(ErrorKind::WouldBlock, "Read timed out"));
}
@ -411,17 +417,33 @@ impl Write for TcpStream {
}
if total_tx == 0 && txlen == 0 {
if self.nonblocking {
return Err(Error::new(ErrorKind::WouldBlock, "Write would block, and nonblocking is set"));
return Err(Error::new(ErrorKind::WouldBlock, "Write would block, and nonblocking is set (full)"));
} else {
if let Some(d) = self.write_timeout {
if self.ticktimer.elapsed_ms() - start > d.millis() {
return Err(Error::new(ErrorKind::WouldBlock, "Write would block, and nonblocking is set"));
if self.ticktimer.elapsed_ms() - start > d.total_millis() {
return Err(Error::new(ErrorKind::WouldBlock, "Write times out, and nonblocking is set (full)"));
}
}
self.ticktimer.sleep_ms(TX_POLL_INTERVAL_MS).unwrap();
}
}
}
rkyv::core_impl::ArchivedOption::Some(ArchivedNetMemResponse::SocketInUse) => {
if total_tx == 0 {
if self.nonblocking {
return Err(Error::new(ErrorKind::WouldBlock, "Write would block, and nonblocking is set (in use)"));
} else {
if let Some(d) = self.write_timeout {
if self.ticktimer.elapsed_ms() - start > d.total_millis() {
return Err(Error::new(ErrorKind::WouldBlock, "Write times out, and nonblocking is set (in use)"));
}
}
self.ticktimer.sleep_ms(TX_POLL_INTERVAL_MS).unwrap();
}
} else {
abort = true; // something was already sent, we can safely abort without error
}
}
_ => return Err(Error::new(ErrorKind::Other, "internal error handling Tx")),
}
}

View file

@ -71,10 +71,21 @@ impl<'a> ShellCmdApi<'a> for NetCmd {
Some(Duration::from_millis(5000)),
None) {
Ok(mut stream) => {
log::info!("stream open");
stream.set_read_timeout(Some(Duration::from_millis(1000))).unwrap();
log::trace!("stream open, setting timeouts");
stream.set_read_timeout(Some(Duration::from_millis(10_000))).unwrap();
stream.set_write_timeout(Some(Duration::from_millis(10_000))).unwrap();
log::debug!("read timeout: {:?}", stream.read_timeout().unwrap().unwrap().total_millis());
log::debug!("write timeout: {:?}", stream.write_timeout().unwrap().unwrap().total_millis());
log::info!("my socket: {:?}", stream.socket_addr());
log::info!("peer addr: {:?}", stream.peer_addr());
log::info!("sending GET request");
write!(stream, "GET /{} HTTP/1.1\r\n", path).expect("stream error");
match write!(stream, "GET /{} HTTP/1.1\r\n", path) {
Ok(_) => log::trace!("sent GET"),
Err(e) => {
log::error!("GET err {:?}", e);
write!(ret, "Error sending GET: {:?}", e).unwrap();
}
}
write!(stream, "Host: {}\r\nAccept: */*\r\nUser-Agent: Precursor/0.9.6\r\n", host).expect("stream error");
write!(stream, "Connection: close\r\n").expect("stream error");
write!(stream, "\r\n").expect("stream error");
@ -82,13 +93,13 @@ impl<'a> ShellCmdApi<'a> for NetCmd {
let mut buf = [0u8; 512];
match stream.read(&mut buf) {
Ok(len) => {
log::info!("raw response ({}): {:?}", len, &buf[..len]);
log::trace!("raw response ({}): {:?}", len, &buf[..len]);
write!(ret, "{}", std::string::String::from_utf8_lossy(&buf[..len])).unwrap();
}
_ => write!(ret, "Didn't get response from host").unwrap(),
Err(e) => write!(ret, "Didn't get response from host: {:?}", e).unwrap(),
}
}
_ => write!(ret, "Couldn't connect to {}:80", host).unwrap(),
Err(e) => write!(ret, "Couldn't connect to {}:80: {:?}", host, e).unwrap(),
}
}
_ => write!(ret, "Couldn't resolve {}", host).unwrap(),

View file

@ -3,6 +3,7 @@
#![cfg_attr(target_os = "none", no_main)]
mod api;
mod version;
use std::cmp::Reverse;
use std::collections::BinaryHeap;