Game Development Reference
In-Depth Information
To create multi-line messages, use one \n at the end of each line preceding the last one, and two, at the
end of the final line, as shown in Listing 10-6.
Listing 10-6. An example of a multi-line message used in JSON transmission
data: {\n
data: "msg": "hello server-sent event",\n
data: "id": 42\n
data: }\n\n
Besides, SSE can track message numbers, transmitting the last message's identifier to the server
whenever the connection is broken. Listing 10-7 shows that this is enabled simply by transmitting the
number of the message using a line that begins with id: .
Listing 10-7. A server message stating its own ID
id: 42\n
data: message\n
data: text\n\n
By default, the browser will attempt to reconnect to the server after a three-second time-out expires. We
can modify the time-out by adding a line that begins with retry: stating the time-out in milliseconds, as
shown in Listing 10-8.
Listing 10-8. A message setting reconnection time-out to 5 seconds
retry: 5000\n
data: one more hello world\n\n
Listing 10-9 provides an example of another feature of SSE: the possibility of naming events by adding a
line that begins with event: and ends with a unique message name.
Listing 10-9. Naming an event as “playerlogon”
event: playerlogon\n
data: {"playername": "Sontan"}\n\n
As shown in Listing 10-10, once the event has a unique name, we can subscribe to that event by
specifying its name in place of “message” in the client.
Listing 10-10. Subscribing to a message named “playerlogon”
source.addEventListener('playerlogon', function(e) {
console.log(e.data);
}, false);
The simplicity and flexibility of the protocol, the possibility of using it over regular HTTP, and support by the
majority of modern browsers make Server-Sent Events a highly promising technology.
 
Search WWH ::




Custom Search