Golang Server Events

I would like to do some single threaded data transfer and experiment with SSE vs Websockets.

Using SSE golang server form I find it confusing how to notify the client to end sessions. (for example, the server has finished sending events or the server has suddenly disconnected or the client has lost connectivity)

One thing I need is to reliably know when these trip situations are. Without using timeouts, etc. My experiments so far, when I take the server offline, the client gets EOF. But I am having trouble trying to figure out how to signal from the server to the client that the connection is closed / ended, and then how to handle / read it? Is EOF a reliable way to determine the state of a closed / error / ready state?

Many SSE examples fail to show the client client connection.

Would it be easier with Websockets?

Any experience that is most appreciated.

thank

+3


source to share


1 answer


The SSE standard requires the browser to reconnect automatically after N seconds if the connection is lost or the server intentionally closes the socket. (The default N is 5 in Firefox, 3 in Chrome and Safari, the last time I checked.) So, if desired, you don't need to do anything. (In WebSockets, you'll have to implement this kind of reconnection for yourself.)

If this reconnection is undesirable, you should send a message to the client stating that "show is over, leave." For example. if you are submitting financial data, you can send this on Friday night when the markets close. The client then has to intercept this message and close the connection from its side. (The socket will then disappear, so the server process will be automatically closed.)

In JavaScript and assuming you are using JSON to send data, it looks something like this:

var es = EventSource("/datasource");
es.addEventListener("message", function(e){
  var d = JSON.parse(e.data);
  if(d.shutdownRequest){
    es.close();
    es=null;
    //Tell user what just happened.
    }
  else{
    //Normal processing here
    }
  },false);

      

UPDATE:



You can tell when reconnections are occurring by listening to the "close" event and then looking at e.target.readyState

es.addEventListener("error", handleError, false);
function handleError(e){
  if(e.target.readyState == 0)console.log("Reconnecting...");
  if(e.target.readyState == 2)console.log("Giving up.");
  }

      

No other information is available, but more importantly, it cannot distinguish your server from intentionally closing the connection, your web server crashing, or your client's Internet connection.

Another thing you can tweak is the retry time if the server sent a message retry:NN

. So if you don't want quick reconfigurations, but instead want at least 60 seconds between any reconnection attempts, you can send your server retry:60

.

+4


source







All Articles