Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    JavaScript

    AI in Recruitment: Cases and Trends

    Development

    Transforming Software Development: The Strategic Impact of Microservices

    Programming

    Code Review

    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
    Thursday, September 11
    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 2.
    Programming

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

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

    node_22_pt2

    So, whatever we type, we see the same message to be sent. Let us fix it. We send messages with a POST method. In order to read this method from req, we need to work with it as with a stream. So, let us look at the following scheme that describes a request’s lifecycle, in particular of the req and res objects.

    Node 22 lesson_2

    We’ll need this information later. So, we’ve received a request. If this is a get request, such requests do not have a body. They’ve got only titles: url and other browser ones, which are fully sent and handled immediately. If it is a POST method, it contains a body that needs to be read: work with req as with a stream. In our case, we’ve used this method to send messages because get, as we’ve mentioned earlier, cannot be used to change data. It is good only for getting them. So, we take req and hang needed handlers on it. That’s how it can look like (server.js):

    http.createServer(function(req, res) {
    
        switch (req.url) {
            case '/':
                sendFile("index.html", res);
                break;
    
            case '/subscribe':
                chat.subscribe(req, res);
                break;
    
            case '/publish':
                var body = '';
    
                req
                    .on('readable', function() {
                        var chunk = req.read();
                        if (chunk !== null) {
                            body += chunk;
                        }
                    })
                    .on('end', function() {
                        body = JSON.parse(body);
    
                        chat.publish(body.message);
                        res.end("ok");
                    });
    
                break;
    
    
            default:
                res.statusCode = 404;
                res.end("Not found");
        }
    
    
    }).listen(3000);

    When receiving another data package we add it to a time variable, and when the data are fully received, we process them as JSON, followed by their publication in a chat body.message. This command will send the message to all of those who’ve already subscribed to subscribe. But it will do nothing to a current request, that’s why a current request that the POST has been sent through, needs to be completed by, for example, specifying that everything has gone well.

    res.end("ok")

    Such code will generally work.

    From the other side, if we write it, we suppose our clients are almost saints, they always send a valid JSON, they never want to do something bad, which is surely wrong. Clients may be different. So, let us see what we can change here. The first thing is JSON acceptance for if it is invalid, the command JSON.parse(body)  will show an exception and it will crush the whole process.

    Read More:  How To Use Prospector For Python Static Code Analysis

    So, let us try to catch it. If an error occurred, we respond to a client: we’re sorry, the request you’ve sent, is incorrect. Add it to our case:

    case '/publish':
                var body = '';
    
                req
                    .on('readable', function() {
                        var chunk = req.read();
                        if (chunk !== null) {
                            body += chunk;
                        }
    
                    })
                    .on('end', function() {
    
                        try {
                            body = JSON.parse(body);
                        } catch (e) {
                            res.statusCode = 400;
                            res.end("Bad Request");
                            return;
                        }
                        chat.publish(body.message);
                        res.end("ok");
                    });
    
                break;
    

    That is exactly code 400, and you need to end your conversation to them. Another safety problem urgent for us is our work with the memory. If a client is too angry or, on the contrary, too generous and wants to send us all of his hard disk content, all the data he will send will endlessly get stored within the variable body and will soon overload all of the memory space causing the server crash. So, in order to avoid it, let us add a little check to our case '/publish'  :

    case '/publish':
                var body = '';
    
                req
                    .on('readable', function() {
                        var chunk = req.read();
                        if (chunk !== null) {
                            body += chunk;
                        }
                        console.log(body.length);
                        if (body.length > 1000) {
                            res.statusCode = 413;
                            res.end("Your message is too big for my little chat");
                        }
                    })
                    .on('end', function() {
                        if (res.statusCode === 413) return;
    
                        try {
                            body = JSON.parse(body);
                        } catch (e) {
                            res.statusCode = 400;
                            res.end("Bad Request");
                            return;
                        }
                        chat.publish(body.message);
                        res.end("ok");
                    });
    
                break;

    If following the certain package a body length is too long, it means 413 – the request body is too big and we also quit communicating with this client. So, let us launch our server and check the chat. It is better to do in two different browsers for your better understanding.

    Read More:  3. Express.js Lessons. Templating with EJS: Layout, Block, Partials

    Well, our chat is ready, but there is one little detail left: so, what happens, if a client ends the connection? Let us look once again at the chat module. Here we can see that incoming clients are added to the array. None of them does not get removed from the array. Respectively, if a client suddenly closes a browser and thus ends the connection, we will see an extra unnecessary connection in this array that has already been closed. On the one hand, it may be quite normal because the connection recording does not bring any downsides – it will mean just nothing. On the other hand, why do we need an extra connection? Fortunately, we can easily catch the moment of closure for this connection:

    exports.subscribe = function(req, res) {
        console.log("subscribe");
    
        clients.push(res);
    
        res.on('close', function() {
            clients.splice(clients.indexOf(res), 1);
        });
    
    
    };

    This event works only if the connection is closed up to its ending by a server, which means either we call res.end, or, if we don’t do this, the connection just cuts off or brings destroy, and it brings close to the event. We remove the connection from the array. This operation can be more effective, if we use object instead of array. But everything will work with the array, too. To make sure, let us do a setInterval that will output the length of a current clients array every 2 seconds:

    setInterval(function() {  
      console.log(clients.length);  
    }, 2000); 
    

    Launch our code in browsers for checking whether the chat works. It does. So, update the page: the current connection will be closed, and a new one will be opened. Update it. As you can see, there are still 2 active connections.

    You will find the lesson code for downloading in our repository.

    node22_2

    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
    Trends February 21, 2019

    4 Tech Factors Driving the World Economy of Tomorrow

    There are 4 factors which will influence the development of the world economy — and they will also change the way we organize our remote workflow.

    Implementing Two-Factor Authentication with NodeJS and otplib

    June 11, 2020

    Getting started with Git Hooks using ghooks

    August 4, 2020

    Amazon S3 Cloud Storage Proxying Through NodeJS from Angular Frontend Securely

    October 28, 2019

    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

    Automated Postgresql Backups with NodeJS and Bash

    JavaScript November 20, 2020

    Follow These Guidelines to Write Testable Code That Can Scale | with Examples

    Programming November 25, 2019

    Integrating Data Privacy into Effective Software Development

    Development December 17, 2024

    Mastering Project Management: Effective Use of Gantt Charts

    JavaScript December 5, 2024

    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
    Node.js

    Create simple POS with React.js, Node.js, and MongoDB #15: Simple RBAC

    E-commerce & Retail

    Strategic Seasonal Campaign Concepts for Online and Retail Markets

    Wiki

    Работа с заказчиком

    Most Popular

    Strategies for Keeping Projects on Track and Meeting Deadlines

    JavaScript

    Essential Strategies for Securing Startup Funding Effectively

    Entrepreneurship

    Key Strategies for Successful Influencer Partnership Negotiations

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

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