SSE communication

  • If your requirement is only to push messages unilaterally, it is recommended to use SSE

Advantages of SSE

  • Real-time: SSE provides a real-time communication mechanism that allows the server to actively push data to the client. This real-time makes SSE particularly suitable for application scenarios that require instant updates, such as real-time chat, online collaboration tools, real-time data display, notification push, etc.

  • Reducing network burden: Compared with the traditional polling method, SSE uses a long connection. Through a single HTTP connection, the server can push multiple events to the client, avoiding frequent HTTP requests, thereby reducing the network burden.

  • Lightweight: SSE is based on the HTTP protocol and is supported by existing server software. Compared with WebSocket, SSE is easier to use.

  • Automatic reconnection: SSE can automatically try to reestablish the connection after the connection is interrupted without the need for additional code. This automatic reconnection mechanism increases the stability of the system and ensures that communication can continue even when the network is unstable.

Implement SSE communication in the plugin

my-nodestack-app
├── src
│   ├── pages
│   │   │── sse      
│   │   │   │── index.js
│   ├── plugins
│   │   │── sse.js    
├── ndsk.config.js
└── package.json
exports.plugin  = {
    name: 'SSE',
    register: async (server) =>{
        const key = '/sse';
        server.event(key);
        server.route({
            method:'GET',
            path:'/SSE',
            handler:(request,h)=>{
                server.events.on(key, async (data) => {
                    h.event({data})
                });
                return h.event({data: {}});
            }
        })

        server.route({
            method:'POST',
            path:'/message',
            handler:(request,h)=>{
                server.events.emit(key, request.payload);
                return 'success'
            }
        })
    }
}
import {useState,useEffect} from 'react'
export default (props)=>{
    let value;
    const [arr,setArr] = useState([])
    const onClick = ()=>{
        fetch('/message',{
            method:"POST",
            body:JSON.stringify({message:value})
        })
    }
    useEffect(()=>{
        new EventSource('/SSE').addEventListener('message',(event)=>{
            const {message} = JSON.parse(event.data);
            if(message){
                arr.push(message);
                setArr([...arr])
            }
        });
    },[]);
    return (
        <html>
            <head>
                <title>{props.title}</title>
            </head>  
            <body> 
                <input onChange={(e)=>{
                    value = e.target.value
                }} type='text' />
                <div>
                    {
                        arr.map((value,k)=>{
                            return (
                                <div key={k}>message: {value}</div>
                            )
                        })
                    }
                </div>
                <button onClick={onClick}>send</button>
            </body>
        </html>
    )
}
  • Visit http://127.0.0.1:3000/sse
  • Note: When not used over HTTP/2, SSE is limited to a maximum number of connections (Chrome, Firefox up to 6 connections per browser)
  • See the SSE documentation here

Next

Socket