So I've been trying to solve this for a few days now.
I have a basic web server that connects to a client with a TcpListener and sends data through a TcpStream.
Sending HTTP responses has been working fine, however when i try to use serve sent events with the EventSource api I've been getting issues.
After reciving the request and determining that its opening an EventSource I do following:
let message = "data: {message: connection established!}\r\n\r\n".to_string();
let res = Response::builder()
.status(StatusCode::OK)
.header("Content-Type", "text/event-stream")
.header("Connection", "keep-alive")
.header("Cache-Control", "no-cache")
.body(message.to_string()).unwrap();
send_response(&mut stream, res).unwrap(); //This function just sends the response through the stream with the write_all method
for _ in 1..10 {
thread::sleep(time::Duration::from_secs_f32(0.3));
stream.write_all(message.as_bytes()).unwrap();
match stream.flush() { Ok(_) => {println!("sent!")}, Err(_) => println!("error!") };
}
match stream.flush() { Ok(_) => {println!("sent!")}, Err(_) => println!("error!") };
I do end up receiving the data, but its all buffered to one response and interpreted as plain text.
I have the page on the client run this script:
const eventSrc = new EventSource("game");
//Create list item for each event message
eventSrc.addEventListener( "message", (event) => {
const newElement = document.createElement("li");
const eventList = document.getElementById("list");
newElement.textContent = `message: ${event.data}`;
eventList.appendChild(newElement);
});
I've double checked that each message is being sent in 0.3 second intervals with curl.
When running with the right request headers I do get the response.
Here's the verbose output:
* Trying 127.0.0.1:7878...
* Connected to localhost (127.0.0.1) port 7878 (#0)
> GET /game HTTP/1.1
> Host: localhost:7878
> User-Agent: curl/7.81.0
> Accept: text/event-stream
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200
< {"content-type": "text/event-stream", "connection": "keep-alive", "cache-control": "no-cache"}
* no chunk, no close, no size. Assume close to signal end
<
data: {message: connection established!}
data: {message: connection established!}
data: {message: connection established!}
ect.
data: {message: connection established!}
* Closing connection 0
I've also tried setting the Transfer-Encoding to buffered with properly formatted messages, and using "\r\n" for each newline, but have gotten the same results.