How can implement SSE Server with com.sun.net.httpserver.HttpServer
I wrote simple HttpHandler
like this for testing connection:
public class SseResource implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.add("Content-Type", "text/event-stream");
responseHeaders.add("Connection", "keep-alive");
responseHeaders.add("Transfer-Encoding", "chunked");
responseHeaders.add("X-Powered-By", "Native Application Server");
exchange.sendResponseHeaders(200, responseHeaders.size());
OutputStream writer = exchange.getResponseBody();
for (int i = 0; i < 10; i++) {
writer.write("event: count\n".getBytes()); // <-- Connection Closed at this line
writer.write(("data: " + i + "\n").getBytes());
writer.write("\n\n".getBytes());
writer.flush();
sleep();
}
writer.close();
}
public static void sleep() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Does not work.
I test connection with Linux curl
command:
curl -Ni http://localhost:8080/stream
HTTP/1.1 200 OK
Connection: keep-alive
X-powered-by: Native Application Server
Date: Thu, 10 Jun 2021 05:27:56 GMT
Transfer-encoding: chunked
Content-type: text/event-stream
Content-length: 4
curl: (18) transfer closed with outstanding read data remaining
Did I misunderstand about SSE server? or does my code have a problem?
response size should be zero.
I compare my response headers with result of this project: https://github.com/enkot/SSE-Fake-Server
exchange.sendResponseHeaders(200, 0);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.