From 29b7a7d08d59040686ea454e33dc8b3626f98606 Mon Sep 17 00:00:00 2001 From: Andrea Ciliberti Date: Fri, 21 Jan 2022 15:59:27 +0100 Subject: [PATCH] Added network-sockets example --- ctru-rs/examples/network-sockets.rs | 69 +++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 ctru-rs/examples/network-sockets.rs diff --git a/ctru-rs/examples/network-sockets.rs b/ctru-rs/examples/network-sockets.rs new file mode 100644 index 0000000..3844b35 --- /dev/null +++ b/ctru-rs/examples/network-sockets.rs @@ -0,0 +1,69 @@ +extern crate ctru; +use ctru::console::Console; +use ctru::gfx::Gfx; +use ctru::services::apt::Apt; +use ctru::services::hid::{Hid, KeyPad}; +use ctru::services::soc::Soc; + +use std::io::{Read, Write}; +use std::net::{Shutdown, TcpListener}; +use std::time::Duration; + +fn main() { + ctru::init(); + let gfx = Gfx::default(); + let _console = Console::init(gfx.top_screen.borrow_mut()); + let hid = Hid::init().unwrap(); + let apt = Apt::init().unwrap(); + + println!("\nlibctru sockets demo\n"); + + let soc = Soc::init().unwrap(); + + let server = TcpListener::bind("0.0.0.0:80").unwrap(); + server.set_nonblocking(true).unwrap(); + + println!( + "Point your browser to http://{}/\n", + soc.host_address() + ); + + while apt.main_loop() { + gfx.wait_for_vblank(); + + match server.accept() { + Ok((mut stream, socket_addr)) => { + println!("Got connection from {}", socket_addr); + + let mut buf = [0u8; 4096]; + match stream.read(&mut buf) { + Ok(_) => { + let req_str = String::from_utf8_lossy(&buf); + println!("{}", req_str); + } + Err(e) => println!("Unable to read stream: {}", e), + } + + let response = b"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\nHello world\r\n"; + + if let Err(e) = stream.write(response) { + println!("Error writing http response: {}", e); + } + + stream.shutdown(Shutdown::Both).unwrap(); + } + Err(e) => match e.kind() { + std::io::ErrorKind::WouldBlock => {} + _ => { + println!("Error accepting connection: {}", e); + std::thread::sleep(Duration::from_secs(2)); + } + }, + } + + hid.scan_input(); + if hid.keys_down().contains(KeyPad::KEY_START) { + break; + }; + } +}