Search code examples
httpserver-sent-events

HTTP 1.1 message protocol and server sent events


As I understand it, in 1.1 normally the browser issues a request and the server makes a single message response. The browser will not issue a new request until it has received the response to the previous message. So what ever response it receives is always interpreted as a response to the last message. Is my understanding correct?

When I open a page in Firefox, the server application parses the following request:

HGet / http/1.1
HeaderField(Host, localhost:8080)
HeaderField(User-Agent, Mozilla/5.0 (X11; Ubuntu; Linux x86_64;rv:41.0)     Gecko/20100101 Firefox/41.0)
HeaderField(Accept, text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8)
HeaderField(Accept-Language, en-GB,en;q=0.5)
HeaderField(Accept-Encoding, gzip, deflate)
HeaderField(Connection, keep-alive)

After responding with the page this would normally be followed by a /favicon.ico request and things precede as expected. But now I have inserted the following line into my javascript to enable server sent events:

var evtSource = new EventSource("/");

which produces a second request:

HGet / http/1.1
HeaderField(Host, localhost:8080)
HeaderField(User-Agent, Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0)
HeaderField(Accept, text/event-stream)
HeaderField(Accept-Language, en-GB,en;q=0.5)
HeaderField(Accept-Encoding, gzip, deflate)
HeaderField(Referer, http://localhost:8080/)
HeaderField(Connection, keep-alive)
HeaderField(Pragma, no-cache)
HeaderField(Cache-Control, no-cache

So can I now send multiple messages when ever I want from the server? (Leaving aside timeout issues) If so how does the browser know to which request, the message (coming from the server) is a response? Does it rely on the contentType header field? Should I use a different uri in the event source? As I'm learning to keep things simple I'm not using encryption, which stops me using HTTP 2. but later I intend to use https. My preference for using the same uri for the normal get and post requests as for the Server Sent Events is that I don't want to put unnecessary information in the unencrypted response line.

Edit: my confusion came from forgetting that http 1.1 browsers will open multiple connections if they need them. So in my simple setup the browser only has one connection open, it converts that one into a Server Sent Event connection and then makes future requests on a new connection with a different client side port number.


Solution

  • So can I now send multiple messages whenever I want from the server?

    Yes.

    how does the browser know to which request, the message (coming from the server) is a response?

    It's not a request. It is an open HTTP connection. So the browser is only receiving events on the open connection that it is holding open.

    Make sense?