Server Sent Events (One Way HTTP protocol)
Before HTML5, there was no standardized technology for server push in HTML, so when real-time information needed to be received on the web, external plugins or Ajax polling techniques that mimicked server push were used.
- WebSocket is mainly used where real-time communication is needed
- SSE establishes a persistent HTTP connection and allows the server to push events to the client; it does not rely on periodic polling (e.g., every 3 seconds).
- Serverless is hard
WebSocket is not always better than SSE. For cases like chat or games where users need to react immediately to server data, WebSocket would be more efficient. However, in many cases, client-side reactions are not necessary.
SSE also has advantages in terms of browser support. When a browser doesn't support WebSocket, the server must implement a separate fallback protocol. On the other hand, since SSE is a client-side technology, if the browser supports JavaScript, it can be implemented using polyfills without making the server-side implementation more complex.
SSE Server
config sse
const headers = { 'Content-Type': 'text/event-stream', 'Connection': 'keep-alive', 'Cache-Control': 'no-cache', }
Notify
const notifyUser = (req, res) => { const payload = {...} clients.forEach(client => client.response.write(`data: ${JSON.stringify(payload)}\n\n`) }
register sse client
const clientId = request.query.clientId clients[clientId] = { response, } request.on('close', () => { delete clients[clientId] })
When sending data, you must add \n\n at the end. The \n\n signals the end of the event stream
SSE Client
useEffect(() => { // 너와 나의 연결고리 만들어 주기 const sseEvents = new EventSource('http://localhost:3000/sse') sseEvents.onopen = function() { // 연결 됐을 때 } sseEvents.onerror = function (error) { // 에러 났을 때 } sseEvents.onmessage = function (stream) { // 메세지 받았을 때 const parsedData = JSON.parse(stream.data) } }, [])

Seonglae Cho

