HTML5 Server-Sent Events prototyping - ambiguous error and repeated polling?

前端 未结 8 1540
野趣味
野趣味 2020-12-03 14:44

I\'m trying to get to grips with Server-Side Events as they fit my requirements perfectly and seem like they should be simple to implement, however I can\'t get past a vague

8条回答
  •  佛祖请我去吃肉
    2020-12-03 15:16

    There is no actual issue with the code, that I can see. The answer selected as correct, is then, incorrect.

    This sums up the behavior mentioned in the question (http://www.w3.org/TR/2009/WD-html5-20090212/comms.html):

    "If such a resource (with the correct MIME type) completes loading (i.e. the entire HTTP response body is received or the connection itself closes), the user agent should request the event source resource again after a delay equal to the reconnection time of the event source. This doesn't apply for the error cases that are listed below."

    The problem lies with the stream. I've successfully kept a single EventStream open before in perl; just send the appropriate HTTP headers, and start sending stream data; never shutdown the stream server side. The issue is that it seems most HTTP libraries attempt to close the stream after its been opened. This will cause the client to attempt to reconnect to the server, which is fully standard compliant.

    This means that it will appear that the problem is solved by running a while loop, for a couple of reasons:

    A) The code will continue to send data, as if it were pushing out a large file B) The code (php server) will never have the chance to attempt to close the connection

    However, the problem here is obvious: to keep the stream alive, a constant stream of data must be sent. This results in wasteful utilization of resources, and negates any benefits the SSE stream is supposed to provide.

    I'm not enough of a php guru to know, but I'd imagine that something in the php server/later in the code is prematurely closing the stream; I had to manipulate the stream at Socket level with Perl to keep it open, since HTTP::Response was closing the connection, and causing the client browser to attempt to re-open the connection. In Mojolicious (another Perl web framework), this can be done by opening a Stream object and setting the timeout to zero, so that the stream never times out.

    So, the proper solution here is not to use a while loop; it is to call the appropriate php functions for opening, and keeping open, a php stream.

提交回复
热议问题