Skip to main content
Redhat Developers  Logo
  • Products

    Platforms

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

    Featured

    • Red Hat build of OpenJDK
    • Red Hat Developer Hub
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat OpenShift Local
    • Red Hat Developer Sandbox

      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Red Hat OpenShift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • See all technologies
    • Programming languages & frameworks

      • Java
      • Python
      • JavaScript
    • System design & architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer experience

      • Productivity
      • Tools
      • GitOps
    • Automated data processing

      • AI/ML
      • Data science
      • Apache Kafka on Kubernetes
    • Platform engineering

      • DevOps
      • DevSecOps
      • Red Hat Ansible Automation Platform for applications and services
    • Secure development & architectures

      • Security
      • Secure coding
  • Learn

    Featured

    • Kubernetes & cloud native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • AI/ML
      AI/ML Icon
    • See all learning resources

    E-books

    • GitOps cookbook
    • Podman in action
    • Kubernetes operators
    • The path to GitOps
    • See all e-books

    Cheat sheets

    • Linux commands
    • Bash commands
    • Git
    • systemd commands
    • See all cheat sheets

    Documentation

    • Product documentation
    • API catalog
    • Legacy documentation
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore the Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

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

    • Run privileged commands more securely in OpenShift Dev Spaces

    • Advanced authentication and authorization for MCP Gateway

    • Unify OpenShift Service Mesh observability: Perses and Prometheus

    • Visualize Performance Co-Pilot data with geomaps in Grafana

    • Integrate a custom AI service with Red Hat Ansible Lightspeed

    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
    © 2025 Red Hat

    Red Hat legal and privacy links

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

    Report a website issue