We do need to flush at the right time

This commit is contained in:
Norbi Peti 2018-01-06 03:04:44 +01:00
parent bab0fe2938
commit 0c00c48003
No known key found for this signature in database
GPG key ID: DBA4C4549A927E56

View file

@ -1,6 +1,8 @@
package buttondevteam.website.page; package buttondevteam.website.page;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket; import java.net.Socket;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -42,9 +44,9 @@ public class BridgePage extends Page {
s = getSocket(exchange); s = getSocket(exchange);
if (s == null) if (s == null)
return new Response(400, "No connection", exchange); return new Response(400, "No connection", exchange);
System.out.println("[" + id + "] PUT " + IOUtils.copy(exchange.getRequestBody(), s.getOutputStream()) System.out.println("[" + id + "] PUT " + copyStream(exchange.getRequestBody(), s.getOutputStream())
+ " bytes into the server"); + " bytes into the server");
s.getOutputStream().flush(); s.getOutputStream().close();
return new Response(200, "OK", exchange); return new Response(200, "OK", exchange);
case "GET": case "GET":
s = getSocket(exchange); s = getSocket(exchange);
@ -53,9 +55,8 @@ public class BridgePage extends Page {
exchange.sendResponseHeaders(200, 0); // Chunked transfer, any amount of data exchange.sendResponseHeaders(200, 0); // Chunked transfer, any amount of data
System.out.println("[" + id + "] Sending to GET"); System.out.println("[" + id + "] Sending to GET");
System.out.println("[" + id + "] Sent to GET " System.out.println("[" + id + "] Sent to GET "
+ IOUtils.copy(s.getInputStream(), exchange.getResponseBody()) + " bytes"); + copyStream(s.getInputStream(), exchange.getResponseBody()) + " bytes");
exchange.getResponseBody().flush(); exchange.getResponseBody().close(); // It'll only get here when the communication is already done
// exchange.getResponseBody().close(); // TO!DO: Keep open? - YES
return null; // Response already sent return null; // Response already sent
case "DELETE": case "DELETE":
System.out.println("[" + id + "] delet this"); System.out.println("[" + id + "] delet this");
@ -98,6 +99,18 @@ public class BridgePage extends Page {
connections.values().remove(socket); connections.values().remove(socket);
} }
private int copyStream(InputStream is, OutputStream os) throws IOException { // Based on IOUtils.copy()
byte[] buffer = new byte[4096];
long count = 0;
int n = 0;
while (-1 != (n = is.read(buffer))) { // Read is blocking
os.write(buffer, 0, n);
count += n;
os.flush();
}
return (int) count;
}
@Override @Override
public boolean exactPage() { public boolean exactPage() {
return false; return false;