Skip to content

Instantly share code, notes, and snippets.

@tomwhoiscontrary
Created May 7, 2019 13:48
Show Gist options
  • Save tomwhoiscontrary/d006e97b1ed6b5de08d20399191b31a7 to your computer and use it in GitHub Desktop.
Save tomwhoiscontrary/d006e97b1ed6b5de08d20399191b31a7 to your computer and use it in GitHub Desktop.
Java 11 streaming subscription
import com.sun.net.httpserver.HttpServer;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Instant;
import java.util.concurrent.Flow;
public class ClientSubscriptionDemo {
public static void main(String[] args) throws Exception {
int port = 8888;
System.out.println("Starting server");
startServer(port);
System.out.println("Sending request");
HttpResponse<Void> response = HttpClient.newHttpClient().send(HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + port))
.build(),
HttpResponse.BodyHandlers.fromLineSubscriber(new Flow.Subscriber<>() {
@Override
public void onSubscribe(Flow.Subscription subscription) {
System.out.println("Subscribing");
subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(String line) {
System.out.println("Received: " + line);
}
@Override
public void onError(Throwable throwable) {}
@Override
public void onComplete() {}
}));
System.out.println("Status: " + response.statusCode()); // this is never printed!
}
private static void startServer(int port) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress("0.0.0.0", port), 0);
server.createContext("/", http -> {
http.sendResponseHeaders(200, 0);
try (BufferedWriter body = new BufferedWriter(new OutputStreamWriter(http.getResponseBody()))) {
while (true) {
body.write(Instant.now().toString());
body.newLine();
body.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
server.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment