Skip to content

Instantly share code, notes, and snippets.

@TatriX
Last active May 18, 2019 09:36
Show Gist options
  • Save TatriX/65690794de1e7b974605342b74a470b7 to your computer and use it in GitHub Desktop.
Save TatriX/65690794de1e7b974605342b74a470b7 to your computer and use it in GitHub Desktop.
TcpStream & fetch example
<!doctype html>
<html>
<head>
</head>
<body>
<script>
fetch("/img").then(res => res.blob())
.then(blob => {
const img = new Image();
img.src = URL.createObjectURL(blob);
document.body.appendChild(img);
});
</script>
</body>
</html>
use std::io::{self, Write, Read};
use std::net::{TcpListener, TcpStream};
use std::fs::File;
fn handle_client(mut stream: TcpStream) {
let file = File::open("logo.png").unwrap();
let bytes = file.bytes().collect::<io::Result<Vec<_>>>().unwrap();
write!(stream, "HTTP/1.1 200 OK\r\n").unwrap();
write!(stream, "Content-Type: image/png\r\n").unwrap();
write!(stream, "Content-Length: {}\r\n", bytes.len()).unwrap();
write!(stream, "\r\n").unwrap();
stream.write(&bytes).unwrap();
}
fn main() -> io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:34254")?;
// accept connections and process them serially
for stream in listener.incoming() {
handle_client(stream?);
}
Ok(())
}
server {
listen 8888;
root /tmp/tcp-image;
location / {
index index.html index.htm;
}
location /img {
proxy_pass http://127.0.0.1:34254;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment