Python Chatbox – Create a Simple Chat app using Python

Published February 07, 2022

A chat application allows you to send and receive messages instantaneously on both mobile and web applications. The chat application allows communication between two parties: the sender of the message and the recipient. The sender is the one who transmits the message, and the receiver is the person who receives the message.

In this post, we are going to look at how to create a simple chat application using Python. We will build a simple chatbox that will allow different users to connect using the sockets in Python.

Here are the simple steps to create a simple chat application in Python.

 

Step 1: Open your terminal and run the following command: pip3 install colorama to install the Colorama package.  This package is used to change the font color for printing each client's color.

Since we are going to build a chat app using sockets, we will require to create a  client and server.

 

Step 2: First, let's set up the server. The server will monitor incoming client connections and add each new client to the collections. The server will additionally start a new thread for each client that is connected. Our server will be created using the code below.

import socket

from threading import Thread

SERVER_HOST = "0.0.0.0"

SERVER_PORT = 5002

separator_token = "<SEP>"

client_sockets = set()

s = socket.socket()

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

s.bind((SERVER_HOST, SERVER_PORT))

s.listen(5)

print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")

def listen_for_client(cs):

"""

This function keeps listening for a message from the `cs` socket

Whenever a message is received, broadcast it to all other connected clients

"""

while True:

            try:

                msg = cs.recv(1024).decode()

            except Exception as e:

            print(f"[!] Error: {e}")

            client_sockets.remove(cs)

            else:

                msg = msg.replace(separator_token, ": ")

            for client_socket in client_sockets:

            client_socket.send(msg.encode())

while True:

client_socket, client_address = s.accept()

print(f"[+] {client_address} connected.")

    client_sockets.add(client_socket)

t = Thread(target=listen_for_client, args=(client_socket,))

t.daemon = True

t.start()

for cs in client_sockets:

            cs.close()

s.close()

 

Our server has been successfully created. Let's put our servers to the test now.

Python Chatbox

 

Step 3: Let's now build the client for our chat app. The chat app will connect to the server, listen for incoming server messages, and transmit the messages to the server. To construct the client-side, copy and paste the following code into your client-chat.py file:

 

import socket

import random

from threading import Thread

from datetime import datetime

from colorama import, Fore, init, Back

init()

colors = [Fore.BLUE, Fore.CYAN, Fore.GREEN, Fore.LIGHTBLACK_EX,

Fore.LIGHTBLUE_EX, Fore.LIGHTCYAN_EX, Fore.LIGHTGREEN_EX,

Fore.LIGHTMAGENTA_EX, Fore.LIGHTRED_EX, Fore.LIGHTWHITE_EX,

Fore.LIGHTYELLOW_EX, Fore.MAGENTA, Fore.RED, Fore.WHITE, Fore.YELLOW

]

client_color = random.choice(colors)

SERVER_HOST = "127.0.0.1"

SERVER_PORT = 5002

separator_token = "<SEP>"

s = socket.socket()

print(f"[*] Connecting to {SERVER_HOST}:{SERVER_PORT}...")

s.connect((SERVER_HOST, SERVER_PORT))

print("[+] Connected.")

name = input("Enter your name: ")

def listen_for_messages():

while True:

            message = s.recv(1024).decode()

        print("\n" + message)

t = Thread(target=listen_for_messages)

t.daemon = True

t.start()

while True:

to_send =  input()

if to_send.lower() == 'q':

            break

date_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

to_send = f"{client_color}[{date_now}] {name}{separator_token}{to_send}{Fore.RESET}"

    s.send(to_send.encode())

s.close()

 

Step 4: Now, we'll execute our application.  It works as it should.

Python chatbox window using sockets

 

Conclusion: In this python example we created simple chat window using socket library

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

288 Views