Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

Unleashing Power of WebSockets on RHEL 6

April 4, 2013
Bohuslav Kabrda
Related topics:
Linux
Related products:
Red Hat Enterprise Linux

    WebSockets are a rising technology that solves one of the great needs of web development - full duplex communication between a browser (or a different client) and a server.

    Let's imagine a simple scenario - live web chat. In the past, you'd probably use AJAX and polling to make new posts appear in realtime. The downside is that implementing all that is not entirely easy and it tends to put a lot of strain on the server.

    This article will show you how to implement a simple web chat using WebSockets, thus eliminating the above problems. We will be using the Tornado web server with the Flask framework, producing a pure Python solution. To get the maximum out of Python 2.x, we will utilize the python27 Software Collection (SCL). We will also need a newer version of Firefox that supports WebSocket technology, so that we can test from the RHEL 6 machine that we're developing on.

    Installation

    First, let's get Firefox. Firefox fully supports WebSocket from version 11, but we want to be fresh, so let's grab version 19 (64 bit / 32 bit). Just download the archive, unpack it, go to the firefox dir and run ./firefox. If you're already running an instance of a different version of Firefox, you will need to run ./firefox -no-remote -P and create a new profile for the downloaded Firefox - you can't run two different versions with the same profile.

    Second, we need to install the python27 SCL. Download the repofile and add it to your /etc/yum.repos.d. Then just use yum install python27 and that's it.

    The last step is installing Flask and Tornado. First, let's switch to the SCL:

    scl enable python27 bash

    Then create a virtualenv for the new project, enable it and install dependencies:

    virtualenv --system-site-packages flask-websocket-test/venv
    source flask-websocket-test/venv/bin/activate
    pip install flask tornado

    That's it, the environment is ready.

    Implementing the Server Logic

    Let's start by creating the server part. First create the directory structure:

    mkdir -p ~/flask-websocket-test/templates

    Then create ~/flask-websocket-test/__init__.py file:

    import flask
    
    import tornado
    import tornado.websocket
    import tornado.wsgi
    
    app = flask.Flask(__name__)
    
    @app.route('/')
    def index():
        return flask.render_template('index.html')
    
    class ChatWebSocket(tornado.websocket.WebSocketHandler):
        clients = []
    
        def open(self):
            ChatWebSocket.clients.append(self)
    
        def on_message(self, message):
            for client in ChatWebSocket.clients:
                client.write_message(message)
    
        def on_close(self):
            ChatWebSocket.clients.remove(self)
    
    tornado_app = tornado.web.Application([
        (r'/websocket', ChatWebSocket),
        (r'.*', tornado.web.FallbackHandler, {'fallback': tornado.wsgi.WSGIContainer(app)})
    ])
    
    tornado_app.listen(5000)
    tornado.ioloop.IOLoop.instance().start()

    Some comments:

    • Lines 1-5 are the necessary imports.
    • Lines 7-11 construct a simple Flask app that renders the templates/index.html template (we will get to that later).
    • Lines 13-24 are the important ones. Class ChatWebSocket has three methods, that every tornado.websocket.WebSocketHandler needs to override. It operates with class variable clients, that holds all active instances of this class.
      • open method on line 16 is called when a new client is connected and it adds the client to the clients list.
      • on_message method on line 19 writes a message that one client sends to all clients.
      • on_close removes the closing client from the clients list
    • Lines 26-29 just tell Tornado to route /websocket to ChatWebsocketHandler and the rest to the Flask WSGI application.
    • Finally, on lines 31-32 we instantiate and start the IOLoop (so we can run the server by running __init__.py file).

    Implementing the index.html Template

    The last step of the implementation is the creation of the ~/flask-websocket-test/templates/index.html template:

    <html>
      <head>
        <title>WebSocketTest</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
        <script type="text/javascript">
          ws = new WebSocket("ws://127.0.0.1:5000/websocket");
          ws.onmessage = function(msg) {
            $("#discussion").prepend("<p>" + msg.data + "<p>");
          };
          ws.onerror = function(evt) {
            alert("ERROR: "+evt.data);
          };
          function send_message() {
            msg = "<b>" + $("#nick").val() + ": </b>" + $("#message").val();
            ws.send(msg);
          }
        </script>
      </head>
      <body>
        <form>
          <dl>
            <dt>Your nick:</dt><dd><input type="text" id="nick" value="nick"></dd>
            <dt>Message:</dt><dd><textarea id="message"></textarea>
          </dl>
          <button onclick="send_message(); return false;">foo</button>
        </form>
        <div id="discussion">
        </div>
      </body>
    </html>

    What's going on in there?

    • We're using jQuery to get things done quickly and nicely with JavaScript.
    • Method ws.onmessage (lines 7-9) is called whenever the server sends some info through the WebSocket.
    • Function send_message (lines 13-16) is used to send a message to the server through the WebSocket.
    • Remember to replace 127.0.0.1 for the actual IP address/domain name of your server if you want to connect from other machines.

    Testing

    Run the application with python ~/flask-websocket-test/__init__.py (don't forget to be in a SCL-enabled shell). Now open two tabs (or windows) of the downloaded Firefox and enjoy the chat.
    And that's it. You just created your first WebSocket server with 32 lines of Python code and 30 lines of html and JavaScript.

    Last updated: November 2, 2023

    Recent Posts

    • Federated identity across the hybrid cloud using zero trust workload identity manager

    • Confidential virtual machine storage attack scenarios

    • Introducing virtualization platform autopilot

    • Integrate zero trust workload identity manager with Red Hat OpenShift GitOps

    • Best Practice Configuration and Tuning for Linux and Windows VMs

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Chat Support

    Please log in with your Red Hat account to access chat support.