Java SSE服务器和com.sun.net.httpserver.httpserver



如何用com.sun.net.httpserver.HttpServer实现SSE服务器
我为测试连接写了这样的简单HttpHandler

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: countn".getBytes()); // <-- Connection Closed at this line 
writer.write(("data: " + i + "n").getBytes());
writer.write("nn".getBytes());
writer.flush();
sleep();
}
writer.close();
}

public static void sleep() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}    

不起作用
I测试与Linuxcurl命令的连接:

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

我是否误解了SSE服务器?或者我的代码有问题?

响应大小应为零
我将我的响应标头与此项目的结果进行比较:https://github.com/enkot/SSE-Fake-Server

exchange.sendResponseHeaders(200, 0);

最新更新