Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Long links are used in more or less some scenarios in projects, except for some chat projects (two-way data exchange), more commonly seen as: Leaderboard periodic refresh, large screen data dynamic refresh, etc., often we just from the server to obtain data for display, in addition to the original use of timer to send requests to obtain data but also can think of is WebSocket, because WebSocket from 0 integration cost is relatively large, but also need to deal with some states, So you know the EventSource class. It only supports sending text data from the server to the client, using the normal HTTP protocol, but the key is simplicity.

An EventSource is an interface to network events pushed by the server. An EventSource instance opens a persistent connection to the HTTP service, sends events in text/event-stream format, and remains open until asked to close. From (MDN)

The Server-Sent Events specification describes a built-in class EventSource that maintains a connection to the Server and allows Events to be received from it. Similar to WebSocket, the connection is persistent.

EventSource is introduced:

Supplement:

Client code:

Encapsulation EventSourceClient:

export default class EventSourceClient {

    constructor(url) {
        this.url = url;
        this.eventSource = null;
    }

  	// Establish a connection
    connection(openCallback, messageCallback, errorCallback) {
        this.eventSource = new EventSource(this.url);
        this.eventSource.onopen = openCallback;
        this.eventSource.onmessage = messageCallback;
        this.eventSource.onerror = function (e) {
            if (this.readyState == EventSource.CONNECTING) {
                console.log(`Reconnecting (readyState=The ${this.readyState})... `);
            } else {
                errorCallback && errorCallback(e)
            }
        };
    }

  	// Disconnect the connection
    disconnect() {
        this.eventSource && this.eventSource.close();
    }

    addAction(action, fn) {
        this.eventSource && this.eventSource.addEventListener(action, fn); }}Copy the code

Using EventSourceClient:

<script type="module">
    import EventSourceClient from './event-source-client.js'
    const url = 'http://localhost:8080/digits'
    window.esc = new EventSourceClient(url);
</script>
<script>
    function start() {
        window.esc.connection((e) = > {
            console.log('Establish a connection', e);
        }, (e) = > {
            console.log('Receive data', e.data);
        }, (e) = > {
            console.log('Error occurred', e);
        })

        window.esc.addAction('bye'.(e) = > {
            console.log('Custom Action', e.data); })}function stop() {
        window.esc.disconnect();
        console.log('Close connection');
    }
</script>
Copy the code

Server code:

let http = require('http');

function onDigits(req, res) {
    // Set the request header
    res.writeHead(200, {
        'Cache-Control': 'no-cache'.// Support cross-domain requests
        "Access-Control-Allow-Origin": "*".// Return type is text/event-stream
        'Content-Type': 'text/event-stream; charset=utf-8'});let i = 0;
    let timer = setInterval(write, 1000);
    write();
    function write() {
        i++;
        if (i == 4) {
            res.write('event: bye\ndata: bye-bye\n\n');
            clearInterval(timer);
            res.end();
            return;
        }
        res.write('data: ' + i + '\n\n'); }}function accept(req, res) {
    if (req.url == '/digits') {
        onDigits(req, res);
    }
}

http.createServer(accept).listen(8080);
Copy the code

Perform demo:


My name is Xiaoxin.

  • 😇 Familiar with: Android development, front-end development.
  • ðŸĪŠ Understand: back-end development, script development.
  • 🧐 specialty: solve difficult and miscellaneous diseases in coding.
  • 😇 motto: a thousand miles, small streams to become rivers and oceans.