Going Real Time with Typescript and WebSockets.

Pawan Bhandarkar
May 2 · 7 min read

Throughout my bachelor’s degree, I had developed a keen interest in Machine Learning and its applications. So naturally, my four years in college were for the most part spent working on AI projects of varying scales. It was only after graduation did I take my first dip in the ocean of Web Development. This was largely in part because of my new job at a startup that required me to help the company develop software to support a massive ongoing Computer Vision-based project.

But it was only when I wrote my first line of React code, coupled with the elegance of Typescript did I start to truly appreciate the art of GUI development. However, the journey ahead is long and arduous. So this series of posts not only serves as a way for me to internalize some of the concepts but also as a way to share some ideas with others who are just starting. I will walk you through my development process, while describing the caveats faced along the way and how I try to solve them.

In this post, I start by building a simple application that can be used to send real-time chat messages between two or more users.

React

React is a GUI framework developed by Facebook. I quite like React mainly because of two reasons:

  1. It couples HTML with Javascript, allowing you to easily integrate serverside scripting with the display components.
  2. React is quite high performance. It provides you with a plethora of components that can be used to minimize how much and how often the GUI needs to be refreshed.

Typescript

While typescript is generally preferred for larger projects, it can be a huge timesaver once you get used to it. It makes use of interfaces and types to ensure type safety at compile time. This means no more accidentally trying to print the length of a null variable or adding a string to an integer.

Typescript files are saved with the .tsxextension. It is important to differentiate them from the other types of files you might encounter when dealing with React and Javascript such as .js .ts and .jsx

Python

For the server, I use Flask-SocketIO to accept and broadcast messages from various clients using the WebSocket Protocol.

Since you’re reading this article and not one titled “Basics of Web Development”, I will assume some familiarity with React and Python. However, for the uninitiated, I will leave links to all major concepts at the relevant places throughout the article. So let’s get started!

All code used in this article will be in this

Part 1: The Backend.

Generally, whenever I start building a web-based project, I like to start with the backend. This helps me get past most of the heavy lifting right at the start. However since this is a simple project, the backend is fairly simple.

Step 1: Create a conda virtual env and activate it.

It’s always best practice to use a new virtual environment to avoid module version clashes.

conda create -n chatroom python==3.7
conda activate chatroom

Step 2: Install the required python modules

We will be using flask-socketio and gevent to host the websocket server.

pip3 install flask_socketio gevent gevent-websocket

Step 3: Build the server

Thanks to the brilliant minds behind the Flask python library, we can get a WebSocket server up and running in just 12 lines of code as shown below. The only purpose of this server is to accept incoming client connection requests and broadcast the messages to all connected clients.

We can now run out server using

 python3 server.py

Part 2: The Frontend

For the front end, I use React-Typescript. I also use React-Boostrap CSS styling for my components. This is made convenient thanks to thenpm module. Lastly, I also use npm module to set up the client side socket connnection.

Step 1: Create a Typescript Project

Now we get to the most complex part of this project. But don’t worry! We’ll walk through it one step at a time.

Firstly, we need to initialize a new typescript project. The easiest way to do it is to use . Recently, they added support for typescript which cuts down 90% of the headache!

We will also use React-Bootstrap GUI components since it allows us to have a decent looking page without having to dive into the CSS which is outside the scope of this post. We also need to install the corresponding types for typescript to kick in.

npx create-react-app gui --template typescript
cd gui
npm i react-bootstrap bootstrap
npm i @types/react-bootstrap @types/bootstrap --save-dev
npm i socket.io-client @types/socket.io-client

While this should work right out of the box, there’s currently that prevents you from doing so. The following command will fix it:

npm i @types/react --save-dev

Now. You can run npm start and it should load up the landing page for ReactTypescript:

We’re halfway there 🎉

Step 2: Build the GUI

Next, we have to replace the default template with our code and make it look more like a chat app.

The best practice, as described in is to make use of React Context to declare the socket object as a globally accessible component. So let’s create a file called socket.tsx for this purpose and add the following code.

Next, we create a file called ChatRoom.tsx that will contain most of our GUI code. We will make use of React for this purpose.

Note: in the code gists that follow, ... is used to indicate that some code has been omitted to aid in explanation.

First, we create and export a basic functional component with the states we will be using.

In the above gist, the states are:

  1. socket : The context variable which is the socket object.
  2. username : Used to store the identifier for each new user.
  3. message : Used to store the newly typed message before sending.
  4. allMessages : Used to story the chat history.
  5. error : Used to store error messages (Optional).
  6. loggedIn : Used to decide whether to show login page or chat page.

Next, let’s define a hook to react to incoming messages. We will use the useEffect() hook for our purpose.

React Hooks can be a bit challenging sometimes, even for veteran Web Developers. So to quickly summarise the useEffect() Hook, just know that:

  1. The function defined in useEffect(()=>{}) will execute once when the component mounts AND once for every time the variable declared within the box brackets [] changes
  2. They run asynchronously and should be preferred for non-blocking operations such as communicating with a backend.

Next, we will create a function to send messages to the server, when a user clicks the Send Button:

For the above, we also define a typescript interface that is used for messages. i.e, rather than sending a plain message string to the server, we send the message along with the username of the currently logged-in user. This helps differentiate the messages in the chat room.

Finally, we will create a function to set the login status so that we can transition from the login page to the cat page.

Great! We’re almost there! Now all that’s left is to add the actual display components. As described previously, we will use 2 layouts:

Note: The best practice is to use separate files for each React Component. But since I wanted to keep the example project fairly simple, I opted to define them within the main component.

We then add some logic to select the appropriate display component:

Step 3: Putting it all Together

All that’s left now is to bring all these components together in the App.tsx file so that we can run it using npm start .

Step 4: Run the App!

Congratulations on making it to the finish line! You can now run your code and marvel at your newly built chat room! Run the following commands from the root of your project:

python3 server.py
cd gui
npm start

The final app will look something like this. Note that I have launched http://localhost:3000 on two separate browser windows to visualise the real-time communication betweem them.

And that’s a wrap!

Conclusion

Note that even though the end application looks quite simple, you now know enough to apply these concepts to your own projects. Here are some ideas on how you can take this project forward:

  1. Add CSS styling to make it look more appealing
  2. Add support to send images over the Websocket protocol.
  3. Host the application online (ex on Heroku)
  4. Experiment and apply your own ideas to make it stand out!

Thank you for reading this article in its entirety. If you liked it, make sure to share and leave some comments about what you’d like me to cover next. As always, constructive criticism is always welcome! Happy Learning!

Geek Culture

Proud to geek out.

Sign up for Geek Culture Hits

By Geek Culture

Subscribe to receive top 10 most read stories of Geek Culture — delivered straight into your inbox, once a week. 

By signing up, you will create a Medium account if you don’t already have one. Review our for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Geek Culture

A new tech publication by Start it up (https://medium.com/swlh).

Pawan Bhandarkar

Written by

I'm interested in Data Science, video games and art! I'm looking forward to travelling the world, eating food and writing about it.

Geek Culture

A new tech publication by Start it up (https://medium.com/swlh).

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface.

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox.

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store