update
This commit is contained in:
60
public/4/4.html
Normal file
60
public/4/4.html
Normal file
@@ -0,0 +1,60 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Live Python Stream</title>
|
||||
<style>
|
||||
body { font-family: sans-serif; padding: 20px; }
|
||||
button { padding: 8px 16px; }
|
||||
pre { background: #f5f5f5; padding: 10px; border: 1px solid #ccc; white-space: pre-wrap; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Python → Client Streaming</h1>
|
||||
<input id="inputParam" placeholder="Enter param" value="Hello" />
|
||||
<button onclick="chat('inputParam','output')">Start Stream</button>
|
||||
<pre id="output"></pre>
|
||||
|
||||
<script>
|
||||
function chat(inputId, outputId) {
|
||||
const param = document.getElementById(inputId).value;
|
||||
const outputEl = document.getElementById(outputId);
|
||||
outputEl.textContent = '';
|
||||
|
||||
fetch('http://localhost:3000/stream', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ param })
|
||||
})
|
||||
.then(res => {
|
||||
if (!res.ok) throw new Error(res.statusText);
|
||||
const reader = res.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let started = false; // flag for first chunk
|
||||
|
||||
function read() {
|
||||
reader.read().then(({ done, value }) => {
|
||||
if (done) {
|
||||
console.log('chunk finish'); // All chunks received
|
||||
return;
|
||||
}
|
||||
if (!started) {
|
||||
console.log('chunk started'); // First chunk received
|
||||
started = true;
|
||||
}
|
||||
outputEl.textContent += decoder.decode(value);
|
||||
read();
|
||||
}).catch(err => {
|
||||
console.error('Stream error:', err);
|
||||
});
|
||||
}
|
||||
|
||||
read();
|
||||
})
|
||||
.catch(err => {
|
||||
outputEl.textContent = 'Error: ' + err.message;
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user