Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Machine Learning

    NLP Preprocessing using Spacy

    B2B Leads

    Enhancing B2B Lead Generation with Data and Analytics Strategies

    Node.js

    Nodejs Lesson 16: Internals of Nodejs: Event Loop

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Saturday, September 27
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / Programming / 22. Long Polling Chat, POST Reading. Pt 1.
    Programming

    22. Long Polling Chat, POST Reading. Pt 1.

    Ivan RastvorovBy Ivan RastvorovOctober 31, 2016Updated:May 26, 2024No Comments6 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    22. Long Polling Chat, POST Reading. Pt 1.
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link

    Dubai City

    Hey all! The aim of our lesson for today is to learn how to create a Node.js chat. Our first chat will be rather simple. Every person following this url

    http://localhost:3000/

    will automatically enter the room, where it will get messages from another user in the same room. In our case, chatting can exist from different browsers. We will make the chat originally with no users, database or authorization.

    First, let us see, how everything is arranged here.

    Node 22 lesson

    The server chatting algorithm is called long-polling.

    It is very simple, on the one hand, and is perfect for 90% of tasks, when you need to communicate with the server, on the other hand. Take a more precise look at it. When a client wants to receive data from a server, a general request gets sent to the server XMLhttpRequest. The most extraordinary thing here will be the way how a server handles it. The server, upon receiving such request, won’t respond immediately and will leave the request hung up. Later, whenever any data for a client appears, the server will respond on this request. The client will receive a response message, handle and output it and will make a new request to the server. The latter will wait, if it has no data. As soon as it receives any data, it will immediately respond. In fact, it seems like a client tries to keep a working connection to the server to receive the data, once they are ready to be transmitted.

    The respective code at the client’s side looks as follows, so let us create index.html:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
    </head>
    <body class="container">
    <p class="lead">Welcome to our chat!</p>
    
    <form id="publish" class="form-inline">
        <input type="text" name="message"/>
        <input type="submit" class="btn btn-primary" value="Send"/>
    </form>
    
    <ul id="messages"></ul>
    
    <script>
        publish.onsubmit = function() {
    
            var xhr = new XMLHttpRequest();
    
            xhr.open("POST", "/publish", true);
    
            xhr.send(JSON.stringify({message: this.elements.message.value}));
    
            this.elements.message.value = '';
    
            return false;
        };
    
        subscribe();
    
    
        function subscribe() {
    
            var xhr = new XMLHttpRequest();
    
            xhr.open("GET", "/subscribe", true);
    
            xhr.onload = function () {
    
                var li = document.createElement('li');
                li.textContent = this.responseText;
                messages.appendChild(li);
    
                subscribe();
            };
    
            xhr.openerror = xhr.onabort = function () {
                setTimeout(subscribe, 500)
            };
    
            xhr.send('');
        }
    </script>
    </body>
    </html>

    There is a form to send messages and there is a list of messages, where they come. With a submit-form a XMLhttpRequest is created, and the messages get published in a general order at the server. And to get new messages, the long-polling algorithm described above is used. There is a function subscribe that launches XMLhttpRequest and says: accept data from this url. Whenever the server response is received, it will be shown as a message and will call the function subscribe again, which means a new request is made. And this process has a cyclic nature. The only exception is when an error occurs or something goes wrong. In this case, we will send subscribe once again, but with a little pause in order not to “damage” the server.

    Read More:  Optimizing Database Interactions in Python: SQLAlchemy Best Practices

    Pay your attention that the code turns to life the long-polling algorithm. It is not bound to any specific chat – it is just a subscription code to the server’s messages. It can be extended or added with various channels of messages receiving, etc. Right now we won’t do anything of these and will move to Node.js. You can see a little template for the server part in a form of an http server that can return index.html as a main page (let us create server.js and add the respective code):

    var http = require('http');
    var fs = require('fs');
    
    http.createServer(function(req, res) {
        
        switch (req.url) {
            case '/':
                sendFile("index.html", res);
                break;
    
            case '/subscribe':
                //..
                break;
    
            case '/publish':
                //..
                break;
    
            default:
                res.statusCode = 404;
                res.end("Not found");
        }
    
    
    }).listen(3000);
    
    
    function sendFile(fileName, res) {
        var fileStream = fs.createReadStream(fileName);
        fileStream
            .on('error', function () {
                res.statusCode = 500;
                res.end("Server error");
            })
            .pipe(res)
            .on('close', function () {
                fileStream.destroy();
            });
    }
    

    Also there will be two url:  case '/subscribe' for subscribing to messages and  case '/publish'  for sending them. They are exactly the same as you’ve seen in index.html . We will start from subscription.

    The subscribe function from the page index.html will send long requests directly to url subscribe. A client that has sent a request to subscribe, on the one hand, should not receive a response right now, but on the other hand, we should remember it has requested the data in order to send them to it whenever we receive them. To solve this task, let us create a special object called chat. chat.subscribe It will remember a client has come. To do so, we will deliver the objects req and  res to it.
    While chat.publish will send messages to all clients existing at the moment:

    http.createServer(function(req, res) {
    
        switch (req.url) {
            case '/':
                sendFile("index.html", res);
                break;
    
            case '/subscribe':
                chat.subscribe(req, res);
                //..
                break;
    
            case '/publish':
                chat.publish('....');
                //..
                break;
    
            default:
                res.statusCode = 404;
                res.end("Not found");
        }

    We will describe this object in the chat within a separate module that will be placed in a current directory. Let us add a record to server.js:

    var chat = require('./chat');
    

    Create chat.js and add the following code:

    var clients = [];
    
    exports.subscribe = function(req, res) {
        console.log("subscribe");
        
        clients.push(res);
        
    };
    
    exports.publish = function(message) {
        console.log("publish '%s'", message);
    
        clients.forEach(function(res) {
            res.end(message);
        });
    
        clients = [];
    };
    
    

    The module will store the current connection in the clients array.

    Read More:  11 Best Books on DevOps: Comprehensive Overview

    Upon the subscribe command it will add a new object res to this array. We’ll draw your attention to the fact the req objects are not added anywhere. Further we won’t need it and will just send messages to this client, so res will be enough. So, whenever a request at url subscribe happens, the respective object  res will be just added to the clients array. We do no more actions with the connection, that’s why from a client’s side it may look like a request has been hung up and hasn’t received any response. Next, at some point we will receive a message and call exports.publish. And this method must send messages to all subscribed clients. To do so, we create a array cycle and send this response to every client:

    clients.forEach(function(res) {
            res.end(message);
        });

    res.end(message)immediately closes the connection and we clean the clients array because all connections there have already been closed and we do not need them anymore. So, let us check the code. Launch and enter your browser at the chat’s url . Then type something. We see various messages come, but not that one we’ve sent because right now we’ve got a stub in a publish method at the server:

    chat.publish("...");

    to-be-continued_1

    The lesson materials were borrowed from the following screencast.

    We are looking forward to meeting you on our website blog.soshace.com

     

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Ivan Rastvorov
    • Website

    Related Posts

    Mastering REST APIs: Essential Techniques for Programmers

    December 18, 2024

    Crafting Interactive User Interfaces Using JavaScript Techniques

    December 17, 2024

    Effective Strategies for Utilizing Frameworks in Web Development

    December 16, 2024
    Leave A Reply Cancel Reply

    You must be logged in to post a comment.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    JavaScript August 6, 2020

    Performance Optimizations for React Native Applications

    React native has grown to be one of the most popular frameworks for building cross-platform mobile applications. React native allows us to share about 90% of our codebase between multiple platforms while maintaining a native feel and aesthetics.

    Node.js Lesson 3: Node Package Manager

    September 14, 2020

    Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

    August 27, 2025

    How to setup SonarQube in a project on Local Machine.

    April 30, 2023

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    Strategies to Enhance Your LinkedIn Profile for Lead Generation

    LinkedIn November 29, 2024

    How to Upload Images to a Cloud Storage(Imgur) in an Angular Application

    Angular January 13, 2020

    20. Node.js Lessons. Data Streams in Node.JS, fs.ReadStream

    Programming October 25, 2016

    Best Udemy Online Courses to Learn JavaScript, React, Angular, and Node [Only Those Updated in 2019]

    JavaScript June 4, 2019

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    Job

    Web Developer Portfolio: The Definitive 2019 Guide with 15 Portfolio Examples

    LinkedIn

    Strategic LinkedIn Branding: A Key to Effective Lead Generation

    CSS

    Mastering CSS Arrangement: Techniques and Hints

    Most Popular

    Node.js Lesson 7: Console Module

    Node.js

    18 Best Web Development Blogs on Medium

    Blogs

    React Lesson 12: Checking Homework Progress from Lesson 11

    JavaScript
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.