» Python: Make Web Chat App with Socket.IO » 2. Development » 2.1 Initial Version

Initial Version

Create your project folder named lr_webchat_py.

Create a Virtual Environment

It's a good practice to use a virtual environment to isolate your project dependencies. You can create a virtual environment using venv module (built-in to Python 3).

python3 -m venv lrWebChatEnv

Caution:
If you're using git or any other version control system, remember to ignore the virtual environment folder.
e.g. in .gitignore:

+
+lrWebChatEnv/

Activate Virtual Environment

Activate the virtual environment. This step is platform-specific.

On Windows:

lrWebChatEnv\Scripts\activate

On macOS and Linux:

source lrWebChatEnv/bin/activate

Manage dependencies

Create a file named requirements.txt in the root directory of your project. This file will list all the dependencies of your project along with their versions. You can generate this file automatically by using the pip freeze command:

pip3 freeze > requirements.txt

If your virtual environment is set up properly, you should get a empty file named requirements.txt.

Installation

Install python-socketio:

pip3 install python-socketio

You will also need an ASGI server, such as Uvicorn:

pip3 install uvicorn

After installation, update requirements.txt:

pip3 freeze > requirements.txt

This command updates the requirements.txt. It should be something similar to this:

bidict==0.23.1
click==8.1.7
h11==0.14.0
python-engineio==4.9.0
python-socketio==5.11.2
simple-websocket==1.0.0
uvicorn==0.29.0
wsproto==1.2.0

Create main.py:

import socketio

sio = socketio.AsyncServer(async_mode='asgi', cors_allowed_origins='*')
app = socketio.ASGIApp(sio)


@sio.event
async def connect(sid, environ):
    print('A user connected:', sid)

Run the program like this:

uvicorn main:app --port 4000

You will get lines like below:

INFO:     Started server process [93232]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:4000 (Press CTRL+C to quit)

Your chat server is running on port 4000 now.