Browser push comet

Coment technology based on server push event
An EventSource object is defined
The way of pushing events on the server side is that the client will establish a connection to the server when creating an EventSource object, and the server will keep the connection open. When an event occurs, the server will write several lines of text in the connection, and then push is achieved

Long connection is used to push messages

A chestnut, realize a simple chat client

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<script>
    // A simple chat client using EventSource
    var nick = prompt('User nickname');  // The dialog will be used to get the user's nickname
    var input = document.getElementById('input');   // Find the input element
    input.focus();  // Make sure the page gets focus as soon as it loads

    // Register notifications for new messages via EventSource
    var chat = new EventSource('/chat');    // Determine the url of the long connection, so as to establish a long connection. The lower part is the received
    chat.onmessage = (event) => {   // When receiving an event, the properties of the interface will be called to directly capture a message
        var msg = event.data;   // Get text data from event object
        var node = document.createTextNode(msg);    // Put the message into a text node
        var div = document.createElement('div');    // Create a div node
        div.appendChild(node);  // Message as child of div
        document.body.insertBefore(div, input); // Insert div before input
        input.scrollIntoView(); // When the message is long, make sure it is still in the window
    };

    // Use XMLHttpRequest to send the user's message to the server. The following is the sent message
    input.onchange = () => {    // Bind the onchange event, that is, when the user's mouse leaves the text box
        var msg = nick + ":" + input.value; // Combine input
        var xhr = new XMLHttpRequest(); // Create a new XML
        xhr.open('post', '/chat');  // Send message to chat
        xhr.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8');   // Make sure the header information is a message
        xhr.send(msg);  // Send message
        input.value = "";   // Empty messages
    }
</script>
<input id="input" style="width:100%">
</body>
</html>

This is not compatible with Microsoft. You can directly use node.js to receive the post message sent by the client.
Understand, jquery

Tags: xml JQuery

Posted on Sun, 05 Jan 2020 19:21:20 -0800 by scriptkiddie