html_sse
Overview
Traditionally, client sends a request to the server to retrieve data; that is, client requests data from the server. With server-sent events(SSE), it’s possible for a server to send new data to client at any time, but only server can send message, one way communication
.
Client with http GET method to
setup a connection(keep it), server accepts it and keeps the connection as well, later on server sends event to client by this connection, when server sends event, the event is as TCP payload, not http, no http at all for event sending
.
SSE is useful for stock price update, message notification
. but new way is to use websocket for server event
The message(must be UTF-8 encoded
when sending by server) has below fields, each takes one line when sending
.
- event(optional)
A string identifying the type of event described. If this is specified, an event will be dispatched on the browser to the listener for the specified event name; the website source code should use addEventListener() to listen for named events. The onmessage handler is called if no event name is specified for a message. - data(optional), can be text or json format. can be multiple such field
The data field for the message. When the EventSource receives multiple consecutive lines that begin with data:, it concatenates them, inserting a newline character between each one. Trailing newlines are removed. - id
The event ID to set the EventSource object’s last event ID value.
but on client side, you got the parsed data, an object with below fields mapping to these fields, the name may be different
Client Side
1 | // open a connection and keep it, if disconnect, browser will reconnect automatically. |
Server Side(JS)
Events sent by server
1 | data: some text |
1 | data: another message |
1 | type: userconnect |
1 | // $yarn add express-sse |
1 | var sse = require('./sse').sse; |