Jarvis @ JM.me

Simulate Chatroom IRC in Python

Mar 18 · 10min امیرمحمد

Power of Socket programming in Python

Connections ?!

There are multiple ways to communicate with other people in 2024, as you know there are websites, web apps, native apps to only serve chatting and communicating with each other.

Social Network

Social network now is part of people lives and It can’t be ignored. I don’t like to talk about SC now in this article cause this one is technical article than normal one but I’ll write articles about SC in future.

Explain pls

This is one of the most simple way to show how It’s done in Python, the thing is What’s done ?! This articles shows you how to write an app, simple app to make a server and clients for chatting purpose. Humans are social entities, they can’t live solo, so they talk to each other and communicate. For making simple server and client in python, you ll need to basic knowledge of Network, and layers. TCP/IPs - Layers - Applications and Sockets. Of course python has socket library by itself so you can use it for good to pass the complex part of making server and clients from start.

Why Python ?!

This is good question. Look at this :

Beautiful is better than ugly. Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested
— The Zen of Python [Python reference philosophy]

Why not ? First of all for being DevOps python is essential, second python is easy, third python is one of the most used programming language for writing scripts (network script, game script, A.I scripts …)

Scripts ??

Yes, Python is considered a scripting language. Here’s why:

  • Scripting languages are interpreted: Python code is interpreted line-by-line by an interpreter, rather than compiled into machine code all at once. This makes scripting languages faster to develop with for smaller tasks.
  • Scripting languages are often used for automation: Scripting languages are great for automating repetitive tasks, which is a common use case for Python.

However, Python is also considered a general-purpose programming language. This means it can be used for more complex programming tasks beyond just scripting. Python’s versatility makes it a powerful tool for many different programming applications.

Let us being the process

Pre Setup

I use python 3.12.x, so if you wanna make this by yourself use python 3.12. Also I don’t use any library than socket in this project, for being lightweight. And the OS is not matter really, if you have Windows Specially Windows 10/11 make sure to use WSL which is Linux under Windows, if you have macOS then you are good to go right now but be sure to install python manually cause the default python comes with macOS itself is not really good, and if you are on Linux then I can say you are GEEK dude, come on why are you so nervous on you r OS just continue and skip reading about others OSs :) god damn it, lol. Linux is the best (Nothing is the best). OK …

Packages

Of course we use virtual environments to be like a pro python programmer :) lol. next we use pyenv to install multiple python version and manage them for good. For example we use pyenv versions to see installed python on system.

For more info about pyenv check It’s docs.

Socket in python

You may read my other article in website that I wrote about Socket Programming in Python.

Python is one of the best option to make network tools, because of It’s library capabilities and power horse scripting language by default.

Server.py

This file manage server side of out app, Sending data - receiving data - manage them - connections and ports …

First we need to create a connection network :

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Used socket from socket library which use and initiate hardware and prepare to define host and port

host = socket.gethostname()
port = 9001
server.bind((host, port))

And now we should listen to server interactions to see what would happen in future

server.listen(5)

From this point our server is WORKING.

Note

You may want to config your clients behaviors or server configs from this point forward, so you may write essential codes after declare server and running it.

You can use threading for multi manage the server and clients specially when several users want to connect to the system (server).

t = threading.Thread(target=handle_client, args=(c, addr))
    t.start()

Warning

You should import threading package to your ENV using either pip or install manually. import threading

We have to decode() and encode() our print strings to make it readable by system as Python 3+ needs it.

We define whole server logic in while loop to handle requests and look for messages over network, this way server is always listening for changes over network. we declare try and except for this matter.

Client.py

This file handle client side for our chatroom mini app, things that this file handle are going over network and sent to server side for remain process.

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Define socket and server, next step is object we have to listen on :

host = socket.gethostname()
port = 9001

This step we make a thread and start the package listening :

t = threading.Thread(target=get_new_msg, args=(server,))
t.daemon = True
t.start()

Tip

You can accomplish socket handling without threads too, the things is without thread server listen on RAM every second which allocate RAM every second, It’s not optimize to do it this way.

Also we can listen for a keyword if someone want to exit the chatroom :

while True:
    message = input(str("You : "))

    server.send(message.encode())

    if message == "!q":
        server.close()
        break

Configs

Bridge between server and client handle by socket with host and It’s port, also we listen on thread and exit keyword send by clients to close a connection.

Server broadcast join message to all clients when someone enter chatroom. Also when someone exit chatroom too.

Connection configs are define by clients and handle by server :

def handle_client(c, addr):
    c.send("welcome to chat rome".encode())

    try:
        name = c.recv(1024).decode()
    except:
        print(f"client {addr} disconnected ...!")
        return c.close()

Last things

This is simple not complex python socket programming handle by threading and sockets which introduce in network concepts.

You can even make an exe and upload your codes to your server and make an UI to have a nice social network app by yourself for your own.

For security tips make sure you close host and port and try, except the connections.

> Comment on twitter (X)
 
CC BY-NC-SA 4.0  2009-PRESENT © Nuxsco (AMS) This website rewrite several times from those years up to present