Skip to content

Instantly share code, notes, and snippets.

@Artur-
Last active August 29, 2015 14:26
Show Gist options
  • Save Artur-/56769569bd15d1bd3f05 to your computer and use it in GitHub Desktop.
Save Artur-/56769569bd15d1bd3f05 to your computer and use it in GitHub Desktop.
From cc81debbf5ca6b0979dbb2104b2ac60f6492c86c Mon Sep 17 00:00:00 2001
From: Artur Signell <artur@vaadin.com>
Date: Wed, 29 Jul 2015 18:16:22 +0300
Subject: [PATCH] Use two-step write so Tomcat correctly reports a dead
connection
Change-Id: Ief2a1111926eefcb131d082b453081c705103e86
---
.../org/atmosphere/cpr/AtmosphereResponse.java | 26 ++++++++++++++++++++--
1 file changed, 24 insertions(+), 2 deletions(-)
diff --git a/modules/cpr/src/main/java/org/atmosphere/cpr/AtmosphereResponse.java b/modules/cpr/src/main/java/org/atmosphere/cpr/AtmosphereResponse.java
index c162eca..352ae51 100644
--- a/modules/cpr/src/main/java/org/atmosphere/cpr/AtmosphereResponse.java
+++ b/modules/cpr/src/main/java/org/atmosphere/cpr/AtmosphereResponse.java
@@ -891,7 +891,7 @@ public class AtmosphereResponse extends HttpServletResponseWrapper {
if (isUsingStream()) {
try {
OutputStream o = writeUsingOriginalResponse ? _r().getOutputStream() : getOutputStream();
- o.write(data.getBytes(getCharacterEncoding()));
+ twoStepWrite(o, data.getBytes(getCharacterEncoding()));
} catch (java.lang.IllegalStateException ex) {
logger.trace("", ex);
}
@@ -956,7 +956,7 @@ public class AtmosphereResponse extends HttpServletResponseWrapper {
if (isUsingStream()) {
try {
OutputStream o = writeUsingOriginalResponse ? _r().getOutputStream() : getOutputStream();
- o.write(data);
+ twoStepWrite(o, data);
} catch (java.lang.IllegalStateException ex) {
}
} else {
@@ -1086,6 +1086,28 @@ public class AtmosphereResponse extends HttpServletResponseWrapper {
return new Builder().response(response).build();
}
+ /**
+ * Writes the given data to the given outputstream in two steps with extra
+ * flushes to make servers notice if the connection has been closed. This
+ * enables caching the message instead of losing it, if the client is in the
+ * progress of reconnecting
+ *
+ * @param o the stream to write to
+ * @param data the data to write
+ * @throws IOException if an exception occurs during writing
+ */
+ public void twoStepWrite(OutputStream o, byte[] data) throws IOException {
+ if (data.length > 1) {
+ o.write(data, 0, 1);
+ o.flush();
+ o.write(data, 1, data.length - 1);
+ o.flush();
+ } else {
+ o.write(data);
+ }
+
+ }
+
@Override
public String toString() {
return "AtmosphereResponse{" +
--
2.5.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment