EventSource / eventsource

EventSource client for Node.js and Browser (polyfill)
MIT License
911 stars 252 forks source link

why the EventSourcePolyfill could not get the sse data #325

Open jiangxiaoqiang opened 1 year ago

jiangxiaoqiang commented 1 year ago

I have defined a sse api like this using rust:

use actix_web::{App, HttpResponse, HttpServer, Responder, post, get};
use rust_wheel::common::util::net::{sse_stream::SseStream, sse_message::SSEMessage};
use std::time::{Duration, SystemTime};
use tokio::{
    sync::mpsc::{UnboundedReceiver, UnboundedSender},
    task,
};

#[get("/sse/producer")]
pub async fn sse() -> impl Responder {
    let (tx, rx): (UnboundedSender<SSEMessage>, UnboundedReceiver<SSEMessage>) =
        tokio::sync::mpsc::unbounded_channel();
    task::spawn(async move {
        for _ in 0..5 {
            let message:SSEMessage = SSEMessage::from_data(&"data".to_string(),& "event_type".to_string());
            let send_result = tx.send(message);
            match send_result {
                Ok(_) => {

                }
                Err(err) => {
                    println!("get docs failed, {}", err);
                }
            }
            tokio::time::sleep(Duration::from_secs(1)).await;
        }
    });
    let response = HttpResponse::Ok()
        .content_type("text/event-stream")
        .streaming(SseStream { receiver: Some(rx) });
    response
}

#[actix_web::main]
async fn main() -> Result<(), std::io::Error> {
    HttpServer::new(|| App::new().service(sse).service(sse))
        .bind("127.0.0.1:8000")?
        .run()
        .await
}

and this is the cargo.toml:


[package]
name = "rust-learn"
version = "0.1.0"
edition = "2018"

[dependencies]
tokio = { version = "1.17.0", features = ["full"] }
serde = { version = "1.0.64", features = ["derive"] }
serde_json = "1.0.64"
actix-web = "4"
futures = "0.3"
eventsource = "0.5"
bytes = "1"
reqwest = { version = "0.11.20", features = ["stream"] }
tokio-stream = "0.1"
rust_wheel = { git = "https://github.com/jiangxiaoqiang/rust_wheel.git", branch = "diesel2.0" }
log4rs = "1.2.0"
log = "0.4.0"
actix-rt = "2.4.1"
futures-util = "0.3.28"

when I using EventSourcePolyfill to get the sse stram data like this:

import React from 'react';

const App: React.FC = () => {

  React.useEffect(() => {
    doLocal();
  },[]);

  const doLocal = () => {
    let eventSource = new window.EventSourcePolyfill('http://localhost:3000/sse/producer');
    eventSource.onopen = () => {

    }
    eventSource.onerror = (error:any) => {
      console.log(error)
      eventSource.close();
    }
    eventSource.onmessage = (msg: any) => {
      console.log("origin polly:",msg)
    };
  }
}

could not get the stream response.

image

Am I missing something?

lunalubra commented 1 year ago

I also couldn't get it to log on the network tab. In my case, I was still receiving them, I relized this after adding a console.log