简体   繁体   中英

Error connecting EventSource (Server-sent event) to server

I'm trying to connect a JavaScript EventSource to a Servlet. I have the following JavaScript code:

var eventSource = new EventSource("notify?userId=123456");
eventSource.onopen = function(e){
    console.log("Connection Opened");
};
eventSource.onmessage = function(e){
    console.log("Message: " + e.data);
};
eventSource.onerror = function(e){
    console.log("Error");
};

Where notify is the location of my Servlet (on the Servlet I use @WebServlet("/notify") ) and ?userId=123456 is a parameter I'm trying to pass to the Servlet. In the developer console, the above code does not produce any logs. However, on the server-side I can see that the code did connect, though, whenever I try to send a message to the client the onmessage function is never hit. If I remove the parameter and do something like this:

var eventSource = new EventSource("notify");

In the developer console, every few seconds I get:

Connection Opened
Error

It seems to continuously repeat. What am I missing here?

So, I've come to the conclusion that Server-sent events aren't quite there yet. The reason I was having my issue was that, on the server-side, if there was no userId parameter then I would call return on the method. This would return to the client-side alerting it that the connection is open. Oddly enough, for whatever reason, this causes the onerror method to be called followed by the onopen method. Though, the connection is correctly opened. If I did provide the userId parameter, I would save the context for later use when I needed to send the client information. Little did I know, that this made the client believe it wasn't yet connected. So, the EventSource doesn't register that is open until it receives its first message. To me, this seems a little bit bazaar and I'm sure there may be some other issues and cross-browser differences as well. Therefore, stay away from server-sent events! If you have more information please provide it, thanks.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM